views:

3579

answers:

1

If I set the .NET DirectoryEntry.Path to something like:

LDAP://CN=John Smith,OU=Group Name,DC=example,DC=com

Everything works great, and I get the DirectoryEntry I need. However, I don't know the user's true Common Name (CN). I only know their username, "John.Smith".

So, how can I query the username? I have tried all the following without success:

LDAP://CN=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://sAMAccountName=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://userPrincipalName=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://[email protected],OU=Group Name,DC=example,DC=com
LDAP://uid=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://o=John.Smith,OU=Group Name,DC=example,DC=com
+2  A: 

You can't just query by means of creating an LDAP string - you'll need to use code for that.

Something like:

DirectoryEntry deRoot = new DirectoryEntry("LDAP://yourserver/CN=Users,dc=YourCompany,dc=com");

DirectorySearcher dsFindUser = new DirectorySearcher(deRoot);
dsFindUser.SearchScope = SearchScope.SubTree;

dsFindUser.PropertiesToLoad.Add("sn"); // surname = last name
dsFindUser.PropertiesToLoad.Add("givenName"); // first name

dsFindUser.Filter = string.Format("(&(objectCategory=Person)(anr={0}))", yourUserName);

SearchResult rseult = dsFindUser.FindOne();

if(result != null)
{
   if(result.Properties["sn"] != null)
   {  
      string lastName = result.Properties["sn"][0].ToString();
   }

   if(result.Properties["givenName"] != null)
   {  
      string lastName = result.Properties["givenName"][0].ToString();
   }
}

The full MSDN documentation on the System.DirectoryServices.DirectorySearcher class can be found on MSDN - it has lots of additional properties and settings.

If you're on .NET 3.5, things have gotten quite a bit easier with a strongly-typed library of routines for handling users and groups - see this excellent MSDN article on the topic for more info.

Hope this helps

Marc

marc_s
Well that worked. Thanks for the answer.But, isn't LDAP supposed to be the standard for querying a Directory? So there should be a way to query for a property like a username? If ActiveDirectory can't expose an important property like a user name to an LDAP query, why pretend to support LDAP? As you can tell, I'm still angry at ActiveDirectory.
Robert
Yes, LDAP is definitely the standard for directories - but that doesn't imply there will be a simple URL-based querying capability (altough that's a really good idea!)
marc_s
AD has several possible naming attributes. Which one is Username? sAMAccountName, userPrinicipalName, DN, CN, etc..
geoffc
@geoffc: true - that's why I used the "anr" - ambiguous name resolution - parameter in my LDAP search filter. it covers all those various names in one parameter :-)
marc_s