Search code examples
.netactive-directoryldapdirectoryservices

How can I add a new user to my system's domain using .Net DirectoryServices?


I want to write a Console application which will just add a new User to my own machine's Domain using .Net DirectoryServices API and LDAP.

Do I need admin account Password for the DomainController to do this ?

Do I need to run that Console Application on a machine on that domain only or can be run on other domains too ?

Can somebody provide me an example ?

UPDATE: Fetching the count of users code

DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(&objectClass=User)objectCategory=Person)userPrincipalName=*health2.com))";
search.PropertiesToLoad.Add("sAMAccountName");
SearchResultCollection allUsers = search.FindAll();
for (int usersCount = 0; usersCount < allUsers.Count; usersCount++)
{
    SearchResult result = allUsers[usersCount];
    if (result.Properties["sAMAccountName"].Count > 0)
    {
       string cn = result.Properties["sAMAccountName"][0].ToString();
       Console.WriteLine(cn);
       Console.ReadLine();
    }
}
Console.WriteLine(string.Format(@"Users Count - {0}", allUsers.Count.ToString()));
Console.ReadLine();

Solution

  • If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

    Basically, you can define a domain context and easily find users and/or groups in AD:

    // set up domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
    
    if(user != null)
    {
       // do something here....     
    }
    

    The article I provided a link to also shows how easily you can create a new user and add it to AD:

    // create a user principal object
    UserPrincipal user = new UserPrincipal(ctx, "User1Acct", "pass@1w0rd01", true);
    
    // assign some properties to the user principal
    user.GivenName = "User";
    user.Surname = "One";
    user.UserPrincipalName = "[email protected]";
    
    // force the user to change password at next logon
    user.ExpirePasswordNow();
    
    // save the user to the directory
    user.Save();
    

    The new S.DS.AM makes it really easy to play around with users and groups in AD!