AD PrincipalSearcher:搜索属性不包含某些值的位置

时间:2014-12-23 16:18:51

标签: c# search active-directory principalsearcher

在构建过滤器以查找具有特定值的对象时,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... }

...

1 个答案:

答案 0 :(得分:3)

似乎无法使用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);
        }
    }