Home > Back-end >  How can I find a single user in Active Directory by common name using PrincipalSearcher?
How can I find a single user in Active Directory by common name using PrincipalSearcher?

Time:02-24

I'm trying to use System.DirectoryServices to find the manager of a user. So I use the current code to get the manager.

 string test = string.Empty;
 using(var context = new PrincipalContext(ContextType.Domain))
 {
   using(var user = UserPrincipal.FindByIdentity(context, "user"))
   {                    
     DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
     test = de.Properties["manager"][0].ToString();
   }
 }

The test variable then contains only the CN or common name of the manager. I need to use that common name to get the actual user of the manager. Because I need things like UserID and Email etc.. How can I accomplish that?

CodePudding user response:

The manager attribute contains the distinguished name of the manager's account (the common name is just the CN= portion of the distinguished name).

You can use UserPrincipal.FindByIdentity() with that distinguished name, just like you did with the user:

var manager = UserPrincipal.FindByIdentity(context, test);
  • Related