0

Add User to Active Directory (Domain) using C# and AccountManagement API

by Syed Aziz ur Rahman 10. December 2013 07:31

 

System.DirectoryServices.AccountManagement API has been added to .net in version 3.5. The API makes it very easy to manage Active Directory (Domain) using code (e.g. C# ). The API lets you perform different operations like add user, delete user, check for user existence in very Object Oriented way as compare to the old API i.e. (DirectoryEntry)

To use the API, you have to add reference to "System.DirectoryServices.AccountManagement.dll" in your project.

Here is some basic code to Add User

 

private string OU = "CN=Users,DC=test,DC=domainName,DC=com";
private string adminUserName = "testAdmin";
private string adminPassword = "T3st123";
string domainName = "Test.DomainName.com";

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        AddUser("testUser", "First", "Last", "testPass123");
    }
    catch (AuthenticationException secEx)
    {
        MessageBox.Show(secEx.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    this.Close();
}

private void AddUser(string samAccountName, string firstName, string lastName, string userPass)
{
    //Use admin account if current user does not have Active Directory rights.
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, OU, ContextOptions.SimpleBind, adminUserName, adminPassword))
    {
        //validate the credentials of admin user.
        if (context.ValidateCredentials(adminUserName, adminPassword))
        {
            UserPrincipal userPrincipal = new UserPrincipal(context, samAccountName, userPass, true);
            userPrincipal.GivenName = firstName; //FistName
            userPrincipal.Surname = lastName;  //LastName
            userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname;
            userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname;
            userPrincipal.Save();
            userPrincipal.Dispose();
        }
    }
}

Tags:

DotNet

Powered by BlogEngine.NET 2.5.0.6
Original Design by Laptop Geek, Adapted by onesoft