Acquiring AD OU list

混江龙づ霸主 提交于 2019-12-18 16:57:54

问题


I am looking to be able to pull a list of current OU's from Active Directory I have been looking at some example code online for sometime, but O don't seem to be able to get this to work.

        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();
            }

The error I get is There provider does not support searching and cannot search LDAP://RootDSE Any Ideas? for each of those returned search results I want to add them to a combo box. (shouldn't be too hard)


回答1:


You cannot search on the LDAP://RootDSE level - that's just an "informational" address with some stuff. It doesn't really represent any location in your directory. You need to bind to the default naming context first:

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);

Once you do that, you should be OK to find all OU's in your domain.

And in order to speed things up, I would recommend not searching using objectClass - that property is not indexed in AD. Use objectCategory instead, which is indexed:

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

UPDATE:
I discovered this filter is wrong - even though the objectCategory is shown as CN=Organizational-Unit,..... in the ADSI browser, you need to specify objectCategory=organizationalUnit in the search for it to succeed:

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


来源:https://stackoverflow.com/questions/2903541/acquiring-ad-ou-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!