Saturday, 27 July 2013

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

Advertisements
Advertisements

2 comments:

  1. Amazing things here. I'm very happy to see your post.
    Thank you so much and I'm taking a look forward to touch you.

    Will you please drop me a e-mail?

    My web-site :: Free Registry Repair

    ReplyDelete
  2. Hye.. Thanks for sharing good example ,
    Feel free to check on my side for some example too : www.developersnote.com

    ReplyDelete