Add User to Active Directory





5.00/5 (4 votes)
A simple application for adding users to active directory
- Download Active Directory User Adder (source) - 1.1 MB
- Download Active Directory User Adder (source-noexe) - 380.8 KB
- Download Active Directory User Adder (EXE) - 342.9 KB
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:
string stringDomainName =
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
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: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.UserPrincipal
: Making another user and adding it to active directory is very simple. We just need to initialize an instance ofUserPrincipal
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 ofUserPrincipal
.
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