Sunday, January 18, 2009

How to change Active directory user properties in c#

// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();

domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();

user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;



if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}

if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}

if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}

if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}

user.CommitChanges();

if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();

}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}

// Clean up.
searcher.Dispose();
result = null;
user.Close();

No comments: