Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Add User to Active Directory

5.00/5 (4 votes)
28 Jan 2013CPOL 70.4K   5K  
A simple application for adding users to active directory

Introduction

This tip will show how to add users to active directory without installing Windows server or Active Directory roles and features.

Using the Code

To add a new user to Active Directory, we use three classes:

C#
string stringDomainName = 
    System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
  1. System.Net.NetworkInformation: We want to add another user to our domain, therefore, at first, we should find out our domain name. We find its name by using this code:
  2. PrincipalContext: is a container of domain against which all operations are performed. To add another user, PrincipalContext uses credential specified by username and password. This credential is used to connect to active directory therefore the user with this credential must have permission to add users.
  3. UserPrincipal: Making another user and adding it to active directory is very simple. We just need to initialize an instance of UserPrincipal by using the specified context from the pervious part and also username and password of new user. Then, we just assign input textboxes data to related properties of UserPrincipal.
C#
private void button1_Click(object sender, RoutedEventArgs e)
{
    try
    {
        string stringDomainName = 
        System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        PrincipalContext PrincipalContext4 = 
          new PrincipalContext(ContextType.Domain, stringDomainName, 
          textboxOu.Text, ContextOptions.SimpleBind, textboxAdminUsername.Text, 
          passwordboxAdminPassword.Password);
        UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext4, 
          textboxLonOnName.Text, passwordboxUserPass.Password, true);
 
        //User Logon Name
        UserPrincipal1.UserPrincipalName = textboxSamAccountName.Text;
        UserPrincipal1.Name = textboxName.Text;
        UserPrincipal1.GivenName = textboxGivenName.Text;
        UserPrincipal1.Surname = textboxSurname.Text;
        UserPrincipal1.DisplayName = textboxDisplayName.Text;
        UserPrincipal1.Description = textboxDescription.Text;
        if (radiobuttonEnable.IsChecked == true)
        {
            UserPrincipal1.Enabled = true;
        }
        else
        {
            UserPrincipal1.Enabled = false;
        }
        UserPrincipal1.Save();
        MessageBox.Show("Saved Successfully");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

History

  • 28th January, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)