Update Active Directory in .Net:
We will see a simple example that will update the AD in this
section. For making the understanding simple, we will search for user with
surname “babu” and update their country to India. Updations to a attribute in AD
can be done through DirectoryEntry class by,
DirectoryEntry.Property[“PropertyName”].Value=”new
Value”;
For example:
dir.Properties["mobile"].Value =
"9901999337";
Implementation:
try
{
DirectoryEntry dir = new DirectoryEntry();
dir.Path = "LDAP://YourDomainController
";
DirectorySearcher sea = new
DirectorySearcher(dir);
sea.Filter = "(sn=Babu)";
SearchResultCollection seacoll =
sea.FindAll();
Response.Write(seacoll.Count.ToString());
StringBuilder str = new StringBuilder();
for (int i = 0; i < seacoll.Count; i++)
{
DirectoryEntry d = new
DirectoryEntry();
d.Path = seacoll[i].Path;
d.Properties["co"].Value = "India";
d.CommitChanges();
if
(d.Properties.Contains("sAMAccountName"))
{
str.Append("sAMAccountName =" +
d.Properties["sAMAccountName"].Value + "\n");
}
if (d.Properties.Contains("co"))
{
str.Append("Country =" +
d.Properties["co"].Value + "\n");
}
str.Append("---------" + "\n");
}
txtSummary.Text = str.ToString();
Response.Write("Completed with " +
seacoll.Count.ToString() + " Row(s)");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
For security purposes not every user id in an enterprise
will have the rights to update AD. So, we can update the AD through a service account that has the access to update the AD. DirectoryEntry class will have UserName and Password
property to get the service account informations.
dir.Username = txtServiceUID.Text;
dir.Password = txtServicePwd.Text;
|