2016-01-04 223 views
0

我有一個使用Ldap查詢的組名列表...我已經將列表名稱綁定到WinForms應用程序中的數據網格。當用戶選擇的組名稱中的一個,一個事件被觸發,組名被傳遞到下面的方法: -.NET Active Directory - 獲取特定Active Directory組中的用戶列表

// Get a list of group specific users // 
    private List<Users> GetUsers(string groupName) 
    { 
     List<Users> groupSpecificUsers = new List<Users>(); 
     DirectorySearcher ds = null; 
     DirectoryEntry de = new DirectoryEntry(domainPath); 
     ds = new DirectorySearcher(de); 

     ds.PropertiesToLoad.Add("SAMAccountName"); 
     ds.PropertiesToLoad.Add("member"); 
     ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 
     SearchResult sr = ds.FindOne(); 

     if (sr != null) 
     { 
       // do whatever you need to do with the entry 
     } 

.... return list of users that belong to the specific GroupName .... 

當我把一個斷點在if語句... SR被列爲null ...我不理解爲什麼它的空...即使選定的組明確地有其成員...

我覺得,我不太明白如何使用特定的組名稱ldap查詢...任何人都可以指向正確的方向嗎?

+0

我覺得SR,因爲你是在SAM帳戶名搜索可能是空的但代替您提供組名稱的帳戶名稱。 SAMAccountName應該是用於登錄到AD的名稱。因此,ds.filter行只會返回1個項目(假設某人的帳戶名稱與組名相同) –

回答

1

你必須採取domainPath,我推測性的參數DirectoryEntry對象是在你的代碼字段某處(?)。如果你可以嘗試從根只是在尋找,你可以試試這個代碼,看看你是否得到更好的結果:

// Get a list of group specific users // 
private List<Users> GetUsers(string groupName) 
{ 
    List<Users> groupSpecificUsers = new List<Users>(); 
// MAKE SURE THE NEXT LINE REFLECTS YOUR DOMAIN 
    DirectorySearcher ds = (new DirectoryEntry("LDAP://dc=yourdomain,dc=tld")); 
    ds.PropertiesToLoad.Add("samaccountname"); 
    ds.PropertiesToLoad.Add("member"); 
    ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 
    SearchResult sr = ds.FindOne(); 

    if (sr != null) 
    { 
      // do whatever you need to do with the entry 
    } 

看看這些變化解決您的問題。

+0

謝謝山姆,我得到的錯誤...不能隱式地從目錄條目轉換到目錄搜索器。在LDAP:// dc = yourdomain語句上。 – Philo

+0

我將其更改爲目錄搜索器並修復了語法錯誤。但由於sr的結果仍然爲空... – Philo

+0

語法錯誤的道歉。我也對它進行了測試,但得到的結果。您是否肯定DirectoryEntry的LDAP://參數是正確的,並且該組實際上對成員有用嗎? – Sam

0

我認爲下面一行:

ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 

需要被改爲:

ds.Filter = "(&(objectClass=group)(Group=" + groupName + "))"; 
+0

仍然沒有結果.... null返回sr – Philo

+0

您可能需要添加「ds.PropertiesToLoad 。新增( 「組」);」在運行過濾器之前。 –

+0

仍然沒有去。 //ds.PropertiesToLoad.Add("SAMAccountName「); //ds.PropertiesToLoad.Add("member「); ds.PropertiesToLoad.Add(「Group」); ds.Filter =「(&(objectClass = group)(Group =」+ groupName +「))」; – Philo

0

這是我如何解決它(這是幾乎什麼薩姆說,我調整它多一點用於說明目的): -

  List<Users> groupSpecificUsers = new List<Users>(); 
      DirectoryEntry ROOT = new DirectoryEntry("LDAP://DC=xxx,DC=net"); 
      DirectoryEntry de = ROOT; 

      var sr = new DirectorySearcher(de); 
      sr.PropertiesToLoad.Add("SAMAccountName"); 
      sr.PropertiesToLoad.Add("member"); 
      sr.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 



      if (sr != null) 
      {...whatever...}