Samuel Neff
Samuel Neff

Reputation: 74939

How to get DN for a DirectorySearcher's SearchResult in .NET?

How can we reliably get the DN of a SearchResult?

We've been using SearchResult.Properties["dn"] but recently encountered an installation where this is not supported. This customer has other applications that boil down to calling Win32's ldap_get_dn method, but there doesn't seem to be an equivalent for SearchResult in .NET.

The solution needs to work across LDAP servers, not ActiveDirectory-specific.

Upvotes: 2

Views: 5117

Answers (2)

Samuel Neff
Samuel Neff

Reputation: 74939

It wasn't clear at first but we later found out the SearchResult.Path property contains the DN and can be parsed for it. This worked consistently with all servers we've encountered so far.

SearchResult result;
...
string userDn = result.Path;

// typical Path is
// LDAP://my.ldap.server.com:39/CN=a,CN=b,OU=c
// we want to grab the part after the third '/'
int i = userDn.IndexOf('/', 7);
if (i >= 0 && userDn.Length > i + 1)
{
    userDn = userDn.Substring(i + 1);
}

SearchResult.Path Property

http://msdn.microsoft.com/en-us/library/system.directoryservices.searchresult.path.aspx

Upvotes: 2

Terry Gardner
Terry Gardner

Reputation: 11132

The base object, which is always a distinguished name, is made available via the LDAP search result entry (but not a search result reference). The distinguished name is not an attribute, however.

Upvotes: 0

Related Questions