C# – How to add a user to AD using System.DirectoryServices.AccountManagement

active-directorycdirectoryservicesvb.net

Using the .net 3.5 framework and C# I'm trying to add a new user to AD from C# and can't find any examples. I see that the PrincipalCollection object has an overloaded 'add' method but can't seem to figure out how it works. Can anyone help?

How create a new user object, add it into AD.

Secondly, the user that will be adding in new people may not actually have the security to do this. Is there a way that I can impersonate another user account that will have permissions and add the account that way?

Best Answer

You can add a user like this:

using (var context = new PrincipalContext(ContextType.Domain))
using (var user = new UserPrincipal(context)
{
    UserPrincipalName = "username",
    Enabled = true
})
{
    user.SetPassword("password");
    user.Save();
}

Re: security you can set the application pool identity to use a privileged service account that has permission to write to the Active Directory. Or you can use a constructor overload for PrincipalContext that takes a username and password for the LDAP connection.