简体   繁体   中英

Active Directory - Get Manager account (from Distinguished Name)

I am trying to get the manager's account for a user account in active directory.

Here's the code I have..

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;


DirectoryContext directoryContext = new  DirectoryContext(DirectoryContextType.Domain, "MyDomain");
Domain domain = Domain.GetDomain(directoryContext);

// Find MY directory Entry
DirectorySearcher search = new DirectorySearcher(domain.GetDirectoryEntry())
{
    Filter = String.Format("(SAMAccountName={0})", "<my user id>")
};
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("manager");
DirectoryEntry userAccount = search.FindOne()?.GetDirectoryEntry();

As you can see, there's a property called manager that is requested and comes back as

CN= Manager Name ,OU=Employee,OU=United Kingdom, OU=CompantUsers, DC=MyDomain, DC=xxx,DC=zzzzz

The CN= Manager Name is the full name, not the LoginID/ SAMAccountName (as used when I searched for MY AD entry ... so how can I now find the AD entry for my manager

Ahhh ... When you know the right question to ask then Google knows the answer ... I did not know that the CN..... string was known as a distinguishedName

if (userAccount.Properties["manager"].Value != null)
{
  DirectorySearcher search2 = new DirectorySearcher(domain.GetDirectoryEntry())
  {
    Filter = string.Format("(distinguishedName={0})", userAccount.Properties["manager"].Value)
  };
  search2.PropertiesToLoad.Add("displayName");
  search2.PropertiesToLoad.Add("mail");
  search2.PropertiesToLoad.Add("manager");
  DirectoryEntry mgrAcc = search2.FindOne()?.GetDirectoryEntry();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM