C# – How to you find a user in active directory from C#


I'm trying to figure out how to search AD from C# similarly to how "Find Users, Contacts, and Groups" works in the Active Directory Users and Computers tool. I have a string that either contains a group name, or a user's name (usually in the format firstname middleinitial [if they have one] lastname, but not always). Even if I do a seperate query for groups vs. users, I can't come up with a way to search that captures most user accounts. The Find Users, Contacts, and Groups tool brings them back almost every time. Anyone have any suggestions?

I already know how to use the DirectorySearcher class, the issue is that I can't find a query that does what I'd like. Neither cn nor samaccount name has anything to do with the user's name in this, so I'm unable to search on those. Splitting things up and searching on sn and givenName doesn't catch anywhere near as much as that tool does.

Best Answer

Are you on .NET 3.5 ? If so - AD has great new features in .NET 3.5 - check out this article Managing Directory Security Principals in .NET 3.5 by Ethan Wilanski and Joe Kaplan.

One of the big new features is a "PrincipalSearcher" class which should greatly simplify finding users and/or groups in AD.

If you cannot use .NET 3.5, one thing that might make your life easier is called "Ambiguous Name Resolution", and it's a little known special search filter that will search in just about any name-related attribute all at once.

Specify your LDAP search query like this:

searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", yourSearchTerm)

Also, I would recommend filtering on the "objectCategory" attribute, since that's single-valued and indexed by default in AD, which is a lot faster than using "objectClass".