2012-08-09 44 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; 
     } 

對不起,愚蠢的問題。