4

在构建过滤器以查找具有特定值的对象时,Principal Searcher 似乎做得很好。没有怎么办?例如,我如何构建过滤器以排除名称中带有“Joe”的每个人。下面的代码不起作用。

        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... }

……

4

1 回答 1

4

似乎不可能PrincipalSearcher

两种可能的解决方法:

  1. 用于PrincipalSearcher获取所有用户并在客户端过滤

    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. 使用 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);
        }
    }
    
于 2014-12-25T19:57:18.057 回答