Introduction
I was trying to update the manager name in Active Directory, but I faced some problems while doing that. I searched the Internet, but didn't find anything useful about this topic.
Background
Most user fields in Active Directory can be inserted as normal text, but Manager has a distinguished name syntax attribute (2.5.5.1), so you have to supply a valid DN for it, not just any string.
Using the code
First, you have to use the System.DirectoryServices
and System.DirectoryServices.ActiveDirectory
namespaces.
using System;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
This code does the actual work:
string EmployeeSAM = "tamer.tharwat";
DirectoryEntry objDirEnt = new DirectoryEntry("LDAP://AlfanarCo",
@"alfanar.com\Tamer.Tharwat", "****");
DirectorySearcher mySearcher = new DirectorySearcher(objDirEnt);
mySearcher.PageSize = 10000;
mySearcher.Filter = "(&(objectCategory=user)(samAccountName="+EmployeeSAM+"))";
mySearcher.PropertiesToLoad.Add("samAccountName");
mySearcher.PropertiesToLoad.Add("Manager");
mySearcher.SearchScope = SearchScope.Subtree;
SearchResult result;
SearchResultCollection resultCol = mySearcher.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
result = resultCol[counter];
DirectoryEntry Userde = result.GetDirectoryEntry();
if (result.Properties.Contains("samaccountname"))
{
string ManagerSAM = "aymanb";
DirectorySearcher managerSearcher = new DirectorySearcher(objDirEnt);
managerSearcher.PageSize = 10;
managerSearcher.Filter = "(&(objectCategory=user)(samAccountName=" +
ManagerSAM + "))";
managerSearcher.PropertiesToLoad.Add("DistinguishedName");
managerSearcher.SearchScope = SearchScope.Subtree;
SearchResult managerResult;
SearchResultCollection managerResultCol = managerSearcher.FindAll();
if (managerResultCol != null)
{
managerResult = managerResultCol[0];
string managerName =
(string)managerResult.Properties["DistinguishedName"][0];
(Userde.Properties["Manager"]).Value = managerName;
Userde.CommitChanges();
}
}
}