4

Principal Searcher seems to do a great job when building a filter to find an object with a particular value. What about without? For example How do I build a filter to exclude everyone with "Joe" in their name. The code below would not work.

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal qbeUser = new UserPrincipal(ctx);
        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

         //this is the problem line.  How to format to exclude values with Joe?
         qbeUser.Name != "*Joe*"; 

        srch.QueryFilter = qbeUser;
        foreach (var found in srch.FindAll())
         { do something to non Joe users... }

....

Fred B
  • 175
  • 1
  • 3
  • 11

1 Answers1

4

Seems it's not possible with PrincipalSearcher.

Two possible workaround:

  1. Use PrincipalSearcher to get all users and filter at client side

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    UserPrincipal qbeUser = new UserPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
    
    srch.QueryFilter = qbeUser;
    foreach (var found in srch.FindAll())
    { //filter out users with "Joe" in its name }
    
  2. Use DirectorySearcher

    DirectoryEntry de = new DirectoryEntry("LDAP://domain.com/dc=domain,dc=com", "user", "pwd");
    DirectorySearcher srch = new DirectorySearcher(de);
    
    srch.Filter = "(&(objectCategory=person)(objectClass=user)(!(name=*Joe*)))";
    srch.SearchScope = SearchScope.Subtree;
    // add the attributes
    srch.PropertiesToLoad.Add("distinguishedName");
    using (SearchResultCollection results = srch.FindAll())
    {
        foreach (SearchResult result in results)
        {
            string dn = result.Properties["distinguishedName"][0] as string;
            Console.WriteLine("- {0}", dn);
        }
    }
    
baldpate
  • 1,707
  • 1
  • 14
  • 23
  • Thanks. yeah I eventually did something like option 1. It feels really inefficient to run through the list twice. I had been trying to get away from directory searcher with the assumption that MS was replacing it with this principle approach so -must me more efficient? Perhaps not. – Fred B Dec 26 '14 at 21:49