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