How to retrieve DirectoryEntry from a DirectoryEntry and a DN

14,536
DirectoryEntry User = YourPreExistingUser();

string managerDN = User.Properties["manager"][0].ToString();

// Browse up the object hierarchy using DirectoryEntry.Parent looking for the
// domain root (domainDNS) object starting from the existing user.
DirectoryEntry DomainRoot = User;

do
{
    DomainRoot = DomainRoot.Parent;
}
while (DomainRoot.SchemaClassName != "domainDNS");

// Use the domain root object we found as the search root for a DirectorySearcher
// and search for the manager's distinguished name.
using (DirectorySearcher Search = new DirectorySearcher())
{
    Search.SearchRoot = DomainRoot;

    Search.Filter = "(&(distinguishedName=" + managerDN + "))";

    SearchResult Result = Search.FindOne();

    if (Result != null)
    {
        DirectoryEntry Manager = Result.GetDirectoryEntry();
    }
}
Share:
14,536
palswim
Author by

palswim

Updated on July 25, 2022

Comments

  • palswim
    palswim over 1 year

    I have a DirectoryEntry object representing a user. From the DirectoryEntry.Properties collection, I am retrieving the "manager" property, which will give me a Distinguished Name ("DN") value for the user's manager.

    Can I retrieve a DirectoryEntry object for the manager from just these two objects? If so, how?

    I'm envisioning something like DirectoryEntry.GetEntryFromDN(dnManager);, but I cannot find a similar call.

    Just to clarify, the DirectoryEntry and DN are the only pieces of information I have. I cannot instantiate a new DirectoryEntry because then I would have have to either use the default Directory and credentials or have the Directory name/port and username/password.

  • palswim
    palswim almost 13 years
    But that creates the DirectoryEntry with the default Directory only; I need to account for the Directory not using the machine's default directory. It also looks like you're assuming that I can statically provide the credentials to connect.
  • palswim
    palswim almost 13 years
    I would rather not traverse the directory tree myself or construct a search query, but it looks like this is the best answer for now.
  • Onno
    Onno about 8 years
    It might not be the quickest way ( it seems a tad slow on my machine) but it really helped me for a quick fix. Thnx :)