NetInverse Developers Blog

March 9, 2009
Category: .Net — Tags: , , , , — admin @ 7:15 pm

The code is very simple. You just need to use DirectoryEntry object to locate the local group and the domain user. Then invoke an “Add” operation on the local group object.

public class AdUtil
{
    public static void AddDomainUserToLocalGroup(
        String domain,
        String userName,
        String groupName)
    {
        String groupPath = String.Format("WinNT://{0}/{1},group",
            Environment.MachineName, groupName);
        DirectoryEntry theGroup = new DirectoryEntry(groupPath);

        if (theGroup.SchemaClassName != "Group")
        {
            throw new ArgumentException("The local group specified doesn't exist.");
        } 

        String userPath = String.Format("WinNT://{0}/{1},user", domain, userName);
        theGroup.Invoke("Add", new object[] { userPath });
        theGroup.CommitChanges();
    }
}

©2009 NetInverse. All rights reserved. Powered by WordPress