JensB
JensB

Reputation: 6850

Searching Active Directory users with a contains and OR query

I've written this code to find users with a display name containing a certain string. I would like to improve this query so that it returns anyone that contains the string in either their firstname or lastname or displayname (right now its only filtering on displayname).

Is that possible? I cant seem to find any examples using OR in these queries/filters.

List<ADUser> adUsers = new List<ADUser>();

DirectoryEntry directoryEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);

directorySearcher.PropertiesToLoad.Add("samaccountname");
directorySearcher.PropertiesToLoad.Add("mail");
directorySearcher.PropertiesToLoad.Add("usergroup");
directorySearcher.PropertiesToLoad.Add("displayname");
directorySearcher.PropertiesToLoad.Add("firstname");
directorySearcher.PropertiesToLoad.Add("lastname");

directorySearcher.Filter = "(&(objectClass=User) (displayname=*" + searchQuery + "*))";

SearchResultCollection searchResultCollection = directorySearcher.FindAll();
foreach (SearchResult u in searchResultCollection)
{
    var user = new ADUser()
    {
        UserName = u?.Properties?.Contains("samaccountname") == true ? u?.Properties["samaccountname"][0]?.ToString() : String.Empty,
        DisplayName = u?.Properties?.Contains("displayname") == true ? u?.Properties["displayname"][0]?.ToString() : String.Empty,
        FirstName = u?.Properties?.Contains("firstname") == true ? u?.Properties["firstname"][0]?.ToString() : String.Empty,
        LastName = u?.Properties?.Contains("lastname") == true ? u?.Properties["lastname"][0]?.ToString() : String.Empty,
        Email = u?.Properties?.Contains("mail") == true ? u?.Properties["mail"][0]?.ToString() : String.Empty,
        UserGroup = u?.Properties?.Contains("usergroup") == true ? u?.Properties["usergroup"][0]?.ToString() : String.Empty,
    };
    adUsers.Add(user);
}

Upvotes: 1

Views: 5191

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

You're looking for | which is the OR operator in LDAP:

directorySearcher.Filter = "(&(objectClass=User)(|(displayName=*" + searchQuery + "*)(givenName=*" + searchQuery + "*)(sn=*" + searchQuery + "*)))";

Another option would be to use Ambigious Name Resolution (although this will also apply each word in the search criteria to mail address attributes and the username, not just display name, given name and surname):

directorySearcher.Filter = "(&(objectClass=User)(anr=" + searchQuery + "))";

Upvotes: 4

Related Questions