add a new user to active directory
No Comments
Andy
Categories:
code
Tags:
C#
App.config
Change the following code to what you require
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="LDAP"> <section name="Connection" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <section name="Directory" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <section name="Misc" type="System.Configuration.NameValueSectionHandler, System,Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </sectionGroup> </configSections> <LDAP> <Connection> <add key="Server" value="ServerName" /> <add key="OU" value="OU=Users,DC=Test,DC=Local" /> <add key="Username" value="ServerUsername" /> <add key="Password" value="ServerPassword" /> <add key="DomainRoot" value="Test.Local" /> </Connection> <Directory> <add key="HomeDirectoryPath" value="\\Test\Users\" /> <add key="HomeDrive" value="U" /> </Directory> <Misc> <add key="Email" value="@test.com" /> </Misc> </LDAP> </configuration>
C# Code
The code below does not require changing as it uses the code above
// App.config
private NameValueCollection LdapConnectionConfig = (NameValueCollection)ConfigurationManager.GetSection("Ldap/Connection");
private NameValueCollection LdapDirectoryConfig = (NameValueCollection)ConfigurationManager.GetSection("Ldap/Directory");
private NameValueCollection LdapMiscConfig = (NameValueCollection)ConfigurationManager.GetSection("Ldap/Misc");
public CreateUser(string username, string forename, string surname) {
try
{
// Create Connection to LDAP
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LdapConnectionConfig["Server"], LdapConnectionConfig["OU"]))
{
// Create User Object to Check Already Exist
using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, username))
{
if (userPrincipal == null)
{
// Create User Object - Setting Username, Password and Enabling Account
using (UserPrincipal user = new UserPrincipal(principalContext, username, "xxxx1111!", true))
{
// Assign Properties to User
user.GivenName = forename;
user.Surname = surname;
user.DisplayName = forename + " " + surname; // Forename Surname
user.Name = forename + " " + surname; // Forename Surname
user.EmailAddress = username + LdapMiscConfig["Email"]; // jdoe@test.com
user.HomeDirectory = LdapDirectoryConfig["HomeDirectoryPath"] + username; // C:\Files\USERNAME, \\Server\Files\Username
user.HomeDrive = LdapDirectoryConfig["HomeDrive"]; // U:\
user.UserPrincipalName = username + LdapConnectionConfig["DomainRoot"]; // jdoe@test.local
// User Must Change Password as First Logon
user.ExpirePasswordNow();
// Save User
user.Save();
}
}
}
}
return true;
}
catch (PrincipalException e)
{
return false;
}
}