Saturday, 11 July 2015

Import Bulk AD Users from CSV using C#

In this article. I am going write C# code samples to create bulk AD users from CSV file and create bulk AD users for testing purpose.

Before proceed, consider the CSV file NewUsers.csv which contains set of new Active Directory users to create with the column headers Name, samAccountName and ParentOU.

Create Bulk AD Users from CSV in C#

Note: The value of ParentOU should be enclosed with double quote ("). like "OU=TestOU,DC=TestDomain,DC=Local" since it has the special character comma (,). because in csv file the comma (,) is the key character to split column headers. (Ex file: Download NewUsers.csv)).

We are using the Visual basic class TextFieldParser to read CSV file in C#, to use this class we need to add reference dll Microsoft.VisualBasic.


Create Bulk AD Users from CSV using C#

Create Bulk AD Users from CSV file:

using Microsoft.VisualBasic.FileIO;
using System.DirectoryServices;
// ---------------------------
public static void CreatBulkADUsersFromCSVFile()
{
    string csv_File_Path = @"C:\NewUsers.csv";
    TextFieldParser csvReader = new TextFieldParser(csv_File_Path);
    csvReader.SetDelimiters(new string[] { "," });
    csvReader.HasFieldsEnclosedInQuotes = true;

    // reading column fields 
    string[] colFields = csvReader.ReadFields();
    int index_Name = colFields.ToList().IndexOf("Name");
    int index_samaccountName = colFields.ToList().IndexOf("samAccountName");
    int index_ParentOU = colFields.ToList().IndexOf("ParentOU");
    while (!csvReader.EndOfData)
    {
       // reading user fields 
        string[] csvData = csvReader.ReadFields();
        DirectoryEntry ouEntry = new DirectoryEntry("LDAP://" + csvData[index_ParentOU]);

        try
        {
            DirectoryEntry user = ouEntry.Children.Add("CN="+csvData[index_Name], "user");
            user.Properties["samAccountName"].Value = csvData[index_samaccountName];
            user.CommitChanges();
            ouEntry.CommitChanges();

            int old_UAC = (int)user.Properties["userAccountControl"][0];
            // AD user account disable flag
            int Flag_Acc_Disable = 2;
            // To enable an ad user account, we need to clear the disable bit/flag:
            user.Properties["userAccountControl"][0] = (old_UAC & ~Flag_Acc_Disable);
            user.CommitChanges();

            user.Invoke("SetPassword", new object[] { "MyP@$$w0rd" });
            user.CommitChanges();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    csvReader.Close();
}

Create Bulk AD Users for Testing:

Use the below C# code to create bulk Active Directory users for testing the purpose.
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();

            int old_UAC = (int)userEntry.Properties["userAccountControl"][0];
            // AD user account disable flag
            int Flag_Acc_Disable = 2;
            // To enable an ad user account, we need to clear the disable bit/flag:
            userEntry.Properties["userAccountControl"][0] = (old_UAC & ~Flag_Acc_Disable);
            userEntry.CommitChanges();

            userEntry.Invoke("SetPassword", new object[] { "MyP@$$w0rd" });
            userEntry.CommitChanges();
        }
        catch (Exception ex)
        {
 
        }
    }

Advertisements
Advertisements

No comments:

Post a Comment