Joseph Michael Pesch
VP Programming

LDAP Query to Find a Users Manager Using C#

by 28. May 2011 11:28

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

// Get specific user in domain...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com");
UserPrincipal usp = UserPrincipal.FindByIdentity(ctx, "userid@domain.com");

// Call the GetManager method and get the managers user id...
UserPrincipal mgp = GetManager(ctx, usp);
System.Diagnostics.Debug.WriteLine(mgp.UserPrincipalName);

// Method to find the manager for a specific user...
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user)
{
  if (user != null)
  {
    // Get the DirectoryEntry object of the UserPrincipal object
    var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry;

    if (dirEntryForUser != null)
    {
      // See if the user has a manager assigned and if so return it...
      if (dirEntryForUser.Properties["manager"] != null 
          && dirEntryForUser.Properties["manager"].Count > 0)
      {
        string mgrDN = dirEntryForUser.Properties["manager"][0].ToString();
        // Get the manager UserPrincipal via the DN 
        return UserPrincipal.FindByIdentity(ctx, mgrDN);
      }
    }
  }
  return null;
}

Tags:

C# | LDAP