Search code examples
c#active-directorydirectorysearcher

How can I search users in Active Directory based on surname and first name?


I'm trying to search for users in AD with their surname (sn) and first name (givenName) using DirectorySearcher in .NET.

I can find a user based on sAMAccountname with this code:

 DirectorySearcher searcher1 = new DirectorySearcher(entry);
 searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(SAMAccountname={0}))",aLogin);

 SearchResult results1;
 results1 = searcher1.FindOne();

But when I try to do it with givenName and sn:

DirectorySearcher searcher1 = new DirectorySearcher(entry);
searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1})", aName, aSName);

SearchResultCollection results1;
results1 = searcher1.FindAll();

It doesn't work; the message says "Invalid Filter"; Can I not filter based on givenName and sn?

How can I achieve this?


Solution

  • You're missing a closing parentheses in your filter. Try:

    searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", aName, aSName);