Skip to content
Tags

Using System.DirectoryServices to manipulate local users

by Alex Peck on February 9th, 2009

I needed to create some additional user accounts within a test suite, put them into local groups and retrieve SIDs etc. This is actually pretty easy using the .NET System.DirectoryServices.DirectoryEntry class, providing you run with a user that has sufficient privilege.

After you reference the namespace and .dll, create a machine directory (this can be substituted for active directory):

DirectoryEntry machineDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");

Then you can add a user by adding to the machine directory’s children:

DirectoryEntry user = machineDirectory.Children.Add(userName, "user");
user.Invoke("SetPassword", password); user.CommitChanges();

Similarly, it’s possible to remove the user:

machineDirectory.Children.Remove(user);

This is how to add a user to a group:

DirectoryEntry group = machineDirectory.Children.Find("Guests");
group.Invoke("Add", user.Path.ToString());

Annoyingly, DirectorySearcher doesn’t appear to be supported on a machine directory. Furthermore, it doesn’t seem possible to call find on the children of a DirectoryEntry when the child doesn’t exist. I always receive a  System.Runtime.InteropServices.COMException, and was therefore forced to adopt this rather dirty approach:

try
{
   return machineDirectory.Children.Find(userName, "user") != null;
}
catch
{
   return false;
}

I found this method works to extract the SID from a DirectoryEntry object.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS