2010-05-25 128 views
5

我期望能夠從Active Directory中獲取當前OU的列表我一直在線查看一些示例代碼,但O似乎無法使其工作。獲取AD OU列表

 string defaultNamingContext; 

     DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"); 
     defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); 
     DirectorySearcher ouSearch = new DirectorySearcher(rootDSE, "(objectClass=organizationalUnit)", 
      null, SearchScope.Subtree); 

     MessageBox.Show(rootDSE.ToString()); 
     try 
     { 
      SearchResultCollection collectedResult = ouSearch.FindAll(); 
      foreach (SearchResult temp in collectedResult) 
      { 
       comboBox1.Items.Add(temp.Properties["name"][0]); 
       DirectoryEntry ou = temp.GetDirectoryEntry(); 
      } 

我得到的錯誤是提供程序不支持搜索並且無法搜索LDAP:// RootDSE Any Ideas? 對於每個返回的搜索結果,我想將它們添加到組合框中。 (不應該太難)

回答

10

您不能搜索LDAP://RootDSE級別 - 這只是一個「信息」地址與一些東西。它並不代表您的目錄中的任何位置。您需要綁定到默認命名上下文第一:

string defaultNamingContext; 

DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"); 
defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); 

DirectoryEntry default = new DirectoryEntry("LDAP://" + defaultNamingContext); 

DirectorySearcher ouSearch = new DirectorySearcher(default, 
            "(objectClass=organizationalUnit)", 
            null, SearchScope.Subtree); 

一旦你這樣做,你應該確定找到的所有OU在您的域。

爲了加快速度,我建議不要使用objectClass搜索 - 該屬性是而不是索引在AD。使用objectCategory代替,這是索引:

DirectorySearcher ouSearch = new DirectorySearcher(default, 
            "(objectCategory=Organizational-Unit)", 
            null, SearchScope.Subtree); 

UPDATE:
我發現這個過濾器是錯誤的 - 即使objectCategoryADSI browser顯示爲CN=Organizational-Unit,.....,你需要尋找它來指定objectCategory=organizationalUnit成功:

DirectorySearcher ouSearch = new DirectorySearcher(default, 
            "(objectCategory=organizationalUnit)", 
            null, SearchScope.Subtree); 
+0

我試圖用上面的建議進行搜索,它似乎是一個非常好的主意,雖然它有一個noob嘗試實現它。我改變默認爲'域',我看不出有問題在做,我的問題是該域= System.DirectoryServices.DirectoryEntry,而不是LDAP:// ...雖然這是在其路徑屬性。 – 2010-05-25 10:56:26

+2

只是想我會補充任何後來發現這一點的人。 Server 2003 R2和更早版本不*索引'objectClass',但是2008年和更晚版本。不是對答案的敲門聲!只是新的信息。資料來源:http://msdn.microsoft.com/en-us/library/ms675095(v=vs.85).aspx – klyd 2014-08-29 14:58:20