Updating Active Directory ‘Manager’ field using code snippet
Here is the code snippet to set the user manager field in AD.
let say we want to create a new user with loginname test1 and set the manager field of user “test2” to “test1”
//Creating the user test1
DirectoryEntry myLdapConnection= new DirectoryEntry(LDAPPath, LDAPUser, LDAPPassword, AuthenticationTypes.Secure);
DirectoryEntry test1 = myLdapConnection.Children.Add(“CN=” + “test1”, “user”);
//now get the user with loginname test2
DirectorySearcher directorySearch = new DirectorySearcher(myLdapConnection);
directorySearch.Filter = “(&(objectClass=user)(SAMAccountName=test2*))”;
SearchResult results = directorySearch.FindOne();
if (results != null)
{
DirectoryEntry test2= new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);
}
string distinguishedName=test2.Properties[“distinguishedName”][0].ToString();
//to set the manager field for a user in AD we need to assign it the distinguishedName of the user.
test1.Properties[“manager”] =distinguishedName;
test1.CommitChanges();