Create new Active Directory user in c#

Description

You can create an user in Active Directory by different way of coding. Here I would like write two methods which we can use it for user creation.

Summary

1. Create new Active Directory Users in C# using PrincipalContext
2. Create new Active Directory Users in C# using DirectoryEntry

Create new Active Directory Users in C# using PrincipalContext

To use this class, you need to add reference System.DirectoryServices.AccountManagement.dll

PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, "TestDomain.local","OU=TestOU,DC=TestDomain,DC=local");

  for (int i = 0; i < 3; i++)
  {
    try
     {
       UserPrincipal up = new UserPrincipal(ouContex);
       up.SamAccountName = "TestUser" + i;
       up.SetPassword("password");
       up.Enabled = true;
       up.ExpirePasswordNow();
       up.Save();
     }
   catch (Exception ex)
   {
   }
 }

Create new Active Directory Users in C# using DirectoryEntry

To use this class, you need to add reference System.DirectoryServices.dll

DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");

  for (int i = 3; i < 6; i++)
   {
     try
      {
        DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user");
        childEntry.CommitChanges();
        ouEntry.CommitChanges();
        childEntry.Invoke("SetPassword", new object[] { "password" });
        childEntry.CommitChanges();
      }
     catch (Exception ex)
     {
     }
  }

Thanks,
Morgan
Software Developer

Advertisement

2 thoughts on “Create new Active Directory user in c#”

Leave a Comment