2012-08-09 46 views
2

在C#中查询Active Directory时出现奇怪的问题。DirectorySearcher和PrincipalSearcher的Active Directory不同结果

var ctx = new PrincipalContext(ContextType.Domain, "adr", "usr", "pwd"); 
var entry = new DirectoryEntry("LDAP://" + adr, usr, pwd); 

var searcher = new DirectorySearcher(entry) { Filter = "(&(sAMAccountName=user_to_search))", PageSize = 2000 }; 

foreach (SearchResult searchUser in searcher.FindAll()) 
{ 
    // groups 
    var groups = searchUser.GetPropertyValues("memberof"); 
} 

var groups = UserPrincipal.FindByIdentity(ctx, "usr_to_search").GetGroups(ctx).ToList(); 

但结果是不一样的:

  • PrincipalSearcher回报率14组
  • DirectorySearcher回报率12组

喏,就是这个错误还是我错过了什么?

感谢

+1

那么,你可以找出哪两个** PrincipalSearcher加回来**吗?我相信'PrincipalSearcher'还会返回所谓的用户的“主要群组”,而不是由'DirectorySearcher'代码返回**。但是第二组是什么 - 不知道。尝试列出两项搜索的结果并在此处发布结果!我最感兴趣的是看到结果! – 2012-08-09 15:51:25

+0

小组 - 有趣的想法,第二组是域用户(全局单元)。那么,这里有没有机会使用目录搜索器加载主要组? – Mennion 2012-08-09 15:54:15

+0

那么,'域用户'是用户帐户的默认“主要组”。 – 2012-08-09 15:54:59

回答

2

哦,我的上帝,我有错在我的扩展方法(我< prop.count - 1)。

public static List<string> GetPropertyValues(this SearchResult searchResult,string property) 
     { 
      var prop = searchResult.Properties[property]; 
      var results = new List<string>(); 


      if (prop != null && prop.Count > 0) 
      { 
       for (int i = 0; i < prop.Count - 1; i++) 
       { 
        results.Add(prop[i].ToString()); 
       } 
      } 
      return results; 
     } 

对不起,愚蠢的问题。