2010-05-25 65 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

相关问题