Create new Active Directory User in C#

Description

  In this article, I am going to write C# code snippets to create new Active Directory user and Bulk AD users in different methods.

Summary

  1. Create new Active Directory user in C# using UserPrincipal  
  2. Create new user in Active Directory using C# with DirectoryEntry
  3. Create Bulk AD Users in C#
  4. Create Bulk AD Users From CSV File in C#

Create new Active Directory user in C# using UserPrincipal

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");

  try
   {
     UserPrincipal up = new UserPrincipal(ouContex);
     up.SamAccountName = "NewTestUser";
     up.SetPassword("password");
     up.Enabled = true;
     up.ExpirePasswordNow();
     up.Save();
   }
   catch (Exception ex)
   {
   }

Create new user in Active Directory using C# with DirectoryEntry

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

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

    try
    {
        DirectoryEntry childEntry = ouEntry.Children.Add("CN=NewTestUser", "user");
        childEntry.CommitChanges();
        ouEntry.CommitChanges();
        childEntry.Invoke("SetPassword", new object[] { "password" });
        childEntry.CommitChanges();
    }
    catch (Exception ex)
    {
    }

Create Bulk AD Users in C#

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

    for (int i = 0; i < 10; 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)
        {

        }
    }

Create Bulk AD Users From CSV File in C#

Consider the CSV file All_users.csv which contains set of new AD Users to create with the column header samAccountName.

Create Bulk AD Users from CSV file using Powershell Script

We are using the Visual basic class TextFieldParser to read CSV file, so we need to add reference dll Microsoft.VisualBasic.

static void CreatBulkADUsersFromCSVFile()
    {
        string csvFilePath=@"C:\UsersAdminDesktopAll_users.CSV";

        using (TextFieldParser csvReader = new TextFieldParser(csvFilePath))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;

            // reading column fields 
            string[] colFields = csvReader.ReadFields();

            int index_samaccountName = colFields.ToList().IndexOf("samAccountName");

            while (!csvReader.EndOfData)
            {
                // reading user fields 
                string[] fieldData = csvReader.ReadFields();

                DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOu,DC=YourDomain,DC=local");

                try
                {
                    DirectoryEntry childEntry = ouEntry.Children.Add("CN=" + fieldData[index_samaccountName], "user");
                    childEntry.CommitChanges();
                    ouEntry.CommitChanges();
                    childEntry.Invoke("SetPassword", new object[] { "password" });
                    childEntry.CommitChanges();
                }
                catch (Exception ex)
                {
                }
            }
        }
    }

Thanks,
Morgan
Software Developer


Advertisement

7 thoughts on “Create new Active Directory User in C#”

  1. What is wrong with this code:

    CODE:
    try {
    List ADUsers = new List();
    string admin_userName = "sneakyguy";
    string admin_password = "Password!";
    string domain = "sneaky";
    var context = new PrincipalContext(ContextType.Domain, domain, "OU=Users,DC=Sneaky,DC=com", admin_userName, admin_password);

    UserPrincipal NewUserPrincipal = new UserPrincipal(context, user_name, password, true);

    NewUserPrincipal.UserPrincipalName = user_name;

    NewUserPrincipal.ExpirePasswordNow();
    //NewUserPrincipal.SamAccountName = user_name;
    // company NewUserPrincipal.GetUnderlyingObject.

    //NewUserPrincipal.GivenName = first_name;
    //NewUserPrincipal.Surname = last_name;
    //NewUserPrincipal.DisplayName = user_name;
    //NewUserPrincipal.Enabled = true;

    NewUserPrincipal.Save();
    return "User Saved Sucessfully";
    } catch (Exception ex) {
    return "Error saving user: n" + ex.ToString();
    }

    I keep getting this error:
    System.DirectoryServices.AccountManagement.PrincipalOperationException: There is no such object on the server.

    Reply
    • Seems the OU 'OU=Users,DC=Sneaky,DC=com' not found. If you are targeting default Users container, you need to provide CN=Users since it is container and not an OU.

      So, just change the path as 'CN=Users,DC=Sneaky,DC=com' and check it again.

      Reply

Leave a Comment