如何从Active Directory获取组织单位列表?

12 c# directoryservices

我查看了DirectoryServices类,它似乎是我需要的,但我似乎无法找到获取组织单位集合所需的类/方法.

你们能提出一些建议吗?

mar*_*c_s 19

你需要使用一个合适的DirectorySearcherfrom System.DirectoryServices,你需要搜索organizationalUnitAD类(我建议根据objectCategory哪个是单值和索引进行搜索 - 比使用它快得多objectClass) - 这样的事情:

List<string> orgUnits = new List<string>();

DirectoryEntry startingPoint = new DirectoryEntry("LDAP://DC=YourCompany,DC=com");

DirectorySearcher searcher = new DirectorySearcher(startingPoint);
searcher.Filter = "(objectCategory=organizationalUnit)";

foreach (SearchResult res in searcher.FindAll()) 
{
    orgUnits.Add(res.Path);
}
Run Code Online (Sandbox Code Playgroud)


Jai*_*ill 5

我知道这个线程有点旧,但我最近创建了一种比 DirectorySearcher 提供的更有效的通过 DirectoryEntries 进行操作的方法,并且希望分享,因为这是 Google 上的最高结果。此示例根据最初指定的起点复制 OU 结构。

传递给第一个构造函数的 DN 路径的格式应为“LDAP://OU=StartingOU,DC=test,DC=com”

using System.DirectoryServices;
using System.Threading.Tasks;

public class ADTree
{
    DirectoryEntry rootOU = null;
    string rootDN = string.Empty;
    List<ADTree> childOUs = new List<ADTree>();

    public DirectoryEntry RootOU
    {
        get { return rootOU; }
        set { rootOU = value; }
    }

    public string RootDN
    {
        get { return rootDN; }
        set { rootDN = value; }
    }

    public List<ADTree> ChildOUs
    {
        get { return childOUs; }
        set { childOUs = value; }
    }

    public ADTree(string dn)
    {
        RootOU = new DirectoryEntry(dn);
        RootDN = dn;
        BuildADTree().Wait();
    }

    public ADTree(DirectoryEntry root)
    {
        RootOU = root;
        RootDN = root.Path;
        BuildADTree().Wait();
    }

    private Task BuildADTree()
    {
        return Task.Factory.StartNew(() =>
        {
            object locker = new object();
            Parallel.ForEach(RootOU.Children.Cast<DirectoryEntry>().AsEnumerable(), child =>
            {
                if (child.SchemaClassname.Equals("organizationalUnit"))
                {
                    ADTree ChildTree = new ADTree(child);
                    lock (locker)
                    {
                        ChildOUs.Add(ChildTree);
                    }
                }
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

要构建,您需要执行以下操作:

ADTree Root = null;

Task BuildOUStructure = Task.Factory.StartNew(() =>
{
    ADTree = new ADTree("LDAP://ou=test,dc=lab,dc=net");
});

BuildOUStructure.Wait();
Run Code Online (Sandbox Code Playgroud)


Lou*_*uis 0

您看过DirectorySearcher方法吗?

以下是MSDNbytes.com上的一些示例。