C#列出Active Directory中的子OU

时间:2015-11-20 05:12:34

标签: c# active-directory

有没有办法在父OU下获取OU列表?现在我可以获得所有OU的列表,但我只想要在测试OU下的那些。这段代码为我提供了所有现有的OU。我如何更改过滤器以便它只显示受测试的OU?

private void oulist_TextChanged(object sender, EventArgs e)
{
    string defaultNamingContext;

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

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

    //MessageBox.Show(rootDSE.Path.ToString());
    SearchResultCollection collectedResult = ouSearch.FindAll();

    try
    {
        foreach (SearchResult temp in collectedResult)
        {
            oulist.Items.Add(temp.Properties["name"][0]);
            DirectoryEntry ou = temp.GetDirectoryEntry();
        }
    }
    catch (Exception ex) { }
}

1 个答案:

答案 0 :(得分:0)

您要搜索的OU可以使用defaultNamingContext作为前缀。

因此,如果您要搜索名为Employees的根级别OU,请将rootDSE行更改为:

rootDSE = new DirectoryEntry("LDAP://OU=Employees," + defaultNamingContext);

并非所有容器都是OU,因此用户例如CN=Users,