15
Dec
.NET Tip: Adding a user to Active Directory in C# with System.DirectoryServices
[csharp]// find the container, ou, whatever that you will be putting your new guy in
string userFolderPath = "LDAP://OU=Headquarters,dc=mhinze,dc=com";
// get a DE representing the ou
DirectoryEntry userFolder = new DirectoryEntry(userFolderPath, USERNAME, PASSWORD);
// name your new guy
string newUserPath = "CN=McTesterson\, Dr. Testy";
// create a DirectoryEntry to represent the new user
DirectoryEntry newUser = userFolder.Children.Add(newUserPath, "User");
// check to see if the new user already exists
if (DirectoryEntry.Exists(newUser.Path)) {
// do stuff, maybe: userFolder.Children.Remove(new DirectoryEntry(newUser.Path));
}
// set all your properties here.. not just these two.. this is sort of tedious work so i left it out
newUser.Properties["samAccountName"].Value = "test";
newUser.Properties["displayName"].Value = "Dr. Testy";
newUser.CommitChanges(); // important
// set the password and the userAccountControl *after* you save the object in ad
newUser.Invoke("setpassword", "p@ssw0rd");
newUser.Properties["userAccountControl"].Value = UserAccountControl.ADS_UF_NORMAL_ACCOUNT;
newUser.CommitChanges(); // important[/csharp]
as an extra bonus, here's an nice enum for userAccountControl that you can perform bitwise manipulations on, etc.
i might edit it to be more user friendly, but i like how it matches up perfectly with the docs
[csharp]
// from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adschema/adschema/a_useraccountcontrol.asp
public enum UserAccountControl
{
ADS_UF_SCRIPT = 0×00000001,
ADS_UF_ACCOUNTDISABLE = 0×00000002,
ADS_UF_HOMEDIR_REQUIRED = 0×00000008,
ADS_UF_LOCKOUT = 0×00000010,
ADS_UF_PASSWD_NOTREQD = 0×00000020,
ADS_UF_PASSWD_CANT_CHANGE = 0×00000040,
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0×00000080,
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0×00000100,
ADS_UF_NORMAL_ACCOUNT = 0×00000200,
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0×00000800,
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0×00001000,
ADS_UF_SERVER_TRUST_ACCOUNT = 0×00002000,
ADS_UF_DONT_EXPIRE_PASSWD = 0×00010000,
ADS_UF_MNS_LOGON_ACCOUNT = 0×00020000,
ADS_UF_SMARTCARD_REQUIRED = 0×00040000,
ADS_UF_TRUSTED_FOR_DELEGATION = 0×00080000,
ADS_UF_NOT_DELEGATED = 0×00100000,
ADS_UF_USE_DES_KEY_ONLY = 0×00200000,
ADS_UF_DONT_REQUIRE_PREAUTH = 0×00400000,
ADS_UF_PASSWORD_EXPIRED = 0×00800000,
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0×01000000
}
[/csharp]