获取AD OU列表

Ste*_*rby 5 c# directoryservices active-directory

我希望能够从Active Directory中提取当前OU的列表我已经在线查看一些示例代码,但是O似乎无法使其工作.

        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();
            }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是提供商不支持搜索,无法搜索LDAP:// RootDSE任何想法?对于每个返回的搜索结果,我想将它们添加到组合框中.(不应该太难)

mar*_*c_s 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);
Run Code Online (Sandbox Code Playgroud)

完成后,您可以在域中找到所有OU.

为了加快速度,我建议不要使用objectClass- 该属性在AD中编入索引.objectCategory相反,使用索引:

DirectorySearcher ouSearch = new DirectorySearcher(default, 
                                     "(objectCategory=Organizational-Unit)", 
                                     null, SearchScope.Subtree);
Run Code Online (Sandbox Code Playgroud)

更新:
我发现这个过滤器是错误的-尽管objectCategory被显示为CN=Organizational-Unit,.....ADSI浏览器,你需要指定objectCategory=organizationalUnit在寻找它的成功:

DirectorySearcher ouSearch = new DirectorySearcher(default, 
                                     "(objectCategory=organizationalUnit)", 
                                     null, SearchScope.Subtree);
Run Code Online (Sandbox Code Playgroud)

  • 我以为我会为后来发现这个的人添加.Server 2003 R2和更早版本确实*不*索引`objectClass`,但2008年及以后呢.不是敲门答案!只是新的信息.来源:http://msdn.microsoft.com/en-us/library/ms675095(v = vs.85).aspx (2认同)