Creating Active Directory Account using C#

0 views
Skip to first unread message

Jayaraman P.

unread,
Sep 9, 2006, 8:36:18 AM9/9/06
to CShar...@googlegroups.com
Hi Csharp Club Members,

Please find the code below to create the Active directory account. Replace all text box names with your relevant text boxes. And add the relevant namespaces to compile.

- Jayaram.


public bool CreateActiveDirectoryAccount()
{
DirectoryEntry deDirectoryEntry = null;
try
{
// Prepare activce directoy connection string
string strUserOU = "testusers";
string strServerPath = "LDAP://kwt1dcc/";
strServerPath += "OU=" + strUserOU + ",DC=pwctest,DC=com";
string strServerUsername = "administrator";
string strServerPassword = "password";
using (deDirectoryEntry = new DirectoryEntry(strServerPath, strServerUsername, strServerPassword, AuthenticationTypes.Secure))
{
DirectoryEntries deDirectoryEntries = deDirectoryEntry.Children;
// Add the new user
DirectoryEntry deUser = deDirectoryEntries.Add("CN=" + txtFullName.Text.Trim(), "user");
deUser.Properties["name"].Add(txtFullName.Text.Trim());
deUser.Properties["sAMAccountName"].Add(txtUserLogonNamePre2.Text.Trim());
deUser.Properties["givenName"].Add(txtFirstName.Text.Trim());
deUser.Properties["displayName"].Add(txtFullName.Text.Trim());
deUser.Properties["mail"].Add(txtEmail.Text.Trim());
deUser.Properties["department"].Add(txtDepartment.Text.Trim());
deUser.Properties["initials"].Add(txtInitials.Text.Trim());
deUser.Properties["mailNickname"].Add(txtUserLogonName.Text.Trim());
deUser.Properties["sn"].Add(txtLastName.Text.Trim());
deUser.Properties["title"].Add(txtTitle.Text.Trim());
deUser.Properties["userPrincipalName"].Add(txtEmail.Text.Trim());
deUser.Properties["pwdLastSet"].Add(0);
deUser.CommitChanges();

// Set the password
deUser.Invoke("SetPassword", new object[] { txtPassword.Text.Trim() });

// User must alwya change password on next logon
if (chkMustChangePassword.Checked)
deUser.Properties["pwdLastSet"].Value = 0;

int iValue;
// Enable the user
if (chkAccDisabled.Checked == false)
{
iValue = (int)deUser.Properties["userAccountControl"].Value;
deUser.Properties["userAccountControl"].Value = iValue & ~0x0002;
}

// Let the password be required
iValue = (int)deUser.Properties["userAccountControl"].Value;
deUser.Properties["userAccountControl"].Value = iValue & ~0x0020;

deUser.CommitChanges();

string strCacheKey = DummyCacheItemKey + txtEmail.Text.Trim();
HttpContext.Current.Cache.Add(strCacheKey, "Test", null, DateTime.MaxValue,
TimeSpan.FromMinutes(3), CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(CacheItemRemovedBack));
}
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
finally
{
// clear memory resources
if (deDirectoryEntry != null)
deDirectoryEntry.Close();
}
return true;
}

//********* End of line ************ //

Reply all
Reply to author
Forward
0 new messages