Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve DirectoryEntry from a DirectoryEntry and a DN

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.

like image 641
palswim Avatar asked Apr 06 '11 20:04

palswim


1 Answers

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();
    }
}
like image 123
Leslie Linard Avatar answered Oct 06 '22 01:10

Leslie Linard