palswim
palswim

Reputation: 12140

How to traverse Directory with Distinguished Names

If I have a Directory Path (as well as the appropriate credentials) like:

LDAP://directory:389/DC=domain,DC=com

Which classes/methods can I use to access various objects by their Distinguished Name (DN) properties? I have tried the DirectoryEntry class, but have not found any way to retrieve a DirectoryEntry object from a "base" object and a DN.

Example: having the Directory URL above, and the DN CN=User,OU=Development,DC=domain,DC=com, how can I access the DirectoryEntry (or similar) object for LDAP://directory:389/CN=User,OU=Development,DC=domain,DC=com?

I have seen some solutions involving string manipulation of the URL, but I'm looking for a way to accomplish this with normal .NET objects/classes.

Upvotes: 1

Views: 1916

Answers (3)

palswim
palswim

Reputation: 12140

Here is my less-than-ideal method I'm using at the moment:

string GetNewDN(DirectoryEntry deBase, string DN)
{
    try
    {   // Handle the LDAP://example.com:389/DN=string formats
        return (new Uri(deBase.Path)).GetLeftPart(UriPartial.Authority) + "/" + DN.Replace("/", @"\/");
    }
    catch (UriFormatException)
    {   // Handle the LDAP://DN=string formats
        return deBase.Path.Substring(0, deBase.Path.IndexOf(":")) + "://" + DN.Replace("/", @"\/");
    }
}

Upvotes: 0

to StackOverflow
to StackOverflow

Reputation: 124746

Could you use DirectorySearcher to search a subtree from a root DirectoryEntry?

This won't help as you note in your comment. I don't think there's any substitute for parsing DirectoryEntry.Path, extracting the bits you need, and concatenating your DN, escaping any special characters in the DN if needed.

You need everything up to and including the third slash:

LDAP://server:port/relativePath

or the second slash if using serverless binding:

LDAP://relativePath

but there can be ambiguity if relativePath itself contains a slash (which will be escaped with a backslash). So, as you say, string manipulation.

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72660

All is explained here.

Here is an example :

DirectoryEntry userEntry = new DirectoryEntry("LDAP://directory:389/CN=User,OU=Development,DC=domain,DC=com",
                                              "<adminAccountName>",
                                              "<adminPassword");

With a good tutorial here.

Upvotes: 1

Related Questions