user3342256
user3342256

Reputation: 1290

Adding multiple criteria to LDAP searches

I have functioning example code to query all users that match a certain department number and echo all associated LDAP properties for each user:

string attribute = "departmentnumber";
string value = "123";

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://ldap.acme.com:389");
rootEntry.AuthenticationType = AuthenticationTypes.None;

DirectorySearcher searcher = new DirectorySearcher(rootEntry, $"({attribute}={value})");

SearchResultCollection results = searcher.FindAll();

foreach (SearchResult result in searcher.FindAll())
{
    var allLDAPProperties = result.Properties.PropertyNames;

    foreach (var property in allLDAPProperties)
    {
        Console.WriteLine((result.Properties[property.ToString()].Count > 0 ? result.Properties[property.ToString()][0] : string.Empty).ToString());
    }

    Console.WriteLine(Environment.NewLine);
}

Console.ReadKey();

However, I would like to add multiple criterion to my initial search (e.g. Return all users with a "departmentnumber" attribute matching "123" and a "joblevel" attribute matching "5." I'm unable to find the correct way to supply compound filter criteria to DirectorySearcher.

I know I could filter the initial result set down with additional processing in a foreach loop, but I'm trying to be efficient.

Upvotes: 1

Views: 2590

Answers (1)

marc_s
marc_s

Reputation: 755471

In order to specify multiple search criteria for an LDAP search, you need to use the LDAP search filter syntax (described in full detail in the linked documentation).

Basically, if you want two criteria, your search filter would be something like:

(&(departmentnumber=123)(joblevel=5))

Check the linked documentation for a full explanation and more examples.

Upvotes: 1

Related Questions