Search code examples
c#directoryservices

Filter for searching distinquishedname, mail and proxies with directory searcher


I'm currently in the process of implementing a method that returns all emailaddresses found (search parameter is the first part of a mail address) on the active directory. In the first iteration of the method I used the interop methods but they took over 40 seconds to get me the needed results. Then I tried the directory searcher and it returned the results in 2 (or less) seconds. So I'm going down this route now. When I use the following code I get all proxy addresses that have Test as part of their name (if I would use smtp:{0}* I would get all proxy addresses that start with Test).

Now what I'm not sure about is (and what my question is about) how could I expand the filter so that it gets me all entries where proxyaddresses, uniquenames OR main smtp addresses have Test as part of their value (thus for all 3 things at the same time with them being seen as an "OR" filtering instead of an and)?

String emailPart = "Test";
String customFilter = string.Format("(& (proxyaddresses=*{0}*) (objectClass=user))", emailPart);
             using (DirectoryEntry gc = new DirectoryEntry("GC:"))
             {
                 foreach (DirectoryEntry z in gc.Children)
                 {
                     using (DirectoryEntry root = z)
                     {
                         using (DirectorySearcher searcher = new DirectorySearcher(root, customFilter, new String[] { "proxyAddresses", "displayName", "distinguishedName" }))
                         {
                             searcher.ReferralChasing = ReferralChasingOption.All;
                             SearchResultCollection resultCollection = searcher.FindAll();
                             foreach (SearchResult searchResult in resultCollection)
                             {
                                 // Do what I need to do with the search results
                             }
                         }
                     }
                 }
             }

Solution

  • The MSDN Search Filter Syntax page would suggest:

    (&(objectClass=user)(|(proxyAddresses=*{0}*)(displayName=*{0}*)(mail=*{0}*)))
    

    NB: I'm using displayName as an example, because I'm not sure which property you're calling "uniquenames".