Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从Active Directory获取组织单位列表?_C#_Directoryservices - Fatal编程技术网

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

C# 如何从Active Directory获取组织单位列表?,c#,directoryservices,C#,Directoryservices,我研究过这个类,它似乎是我所需要的,但我似乎找不到获取组织单元集合所需的类/方法 你们能给点建议吗?你们看过这个方法了吗 以下是和的一些示例。List source=new List(); DirectoryEntry root=new DirectoryEntry(“LDAP://app.shgbit.com”); DirectoryEntry gbvision=root.Children.Find(“OU=UMP”); DirectorySearcher search=新的Directory

我研究过这个类,它似乎是我所需要的,但我似乎找不到获取组织单元集合所需的类/方法

你们能给点建议吗?

你们看过这个方法了吗

以下是和的一些示例。

List source=new List();
DirectoryEntry root=new DirectoryEntry(“LDAP://app.shgbit.com”);
DirectoryEntry gbvision=root.Children.Find(“OU=UMP”);
DirectorySearcher search=新的DirectorySearcher(gbvision);
searcher.Filter=“(objectClass=computer)”;
int指数=1;
foreach(searcher.FindAll()中的每个SearchResult)
{
var box=each.GetDirectoryEntry();
添加(新的PlayerBO{Id=index++,Name=box.Properties[“Name”].Value.ToString(),Description=box.Properties[“Description”].Value.ToString());
}
ListViewAD.ItemsSource=新的SelectableSource(源);

您需要使用
System.DirectoryServices
中合适的
DirectorySearcher
,并且需要搜索
organizationalUnit
广告类(我建议基于
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);
}
List orgUnits=new List();
DirectoryEntry startingPoint=new DirectoryEntry(“LDAP://DC=YourCompany,DC=com”);
DirectorySearcher search=新的DirectorySearcher(起始点);
searcher.Filter=“(objectCategory=organizationalUnit)”;
foreach(searcher.FindAll()中的SearchResult res)
{
orgUnits.Add(res.Path);
}

我知道这个帖子有点老了,但我最近创建了一种比DirectorySearcher提供的更有效的方法来处理DirectoryEntries,并希望与大家分享,因为这是Google上的最佳结果。此示例基于最初指定的起点复制OU结构

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


这是我的解决方案,它正在发挥作用:

List<string> DisplayedOU = new List<string>();
int step = 0;
string span = "<span style='margin-left:6px;'> -- </span>";

private void getOU2()
{
    string strRet = "";
    DirectoryEntry domainRoot = new DirectoryEntry("LDAP://uch.ac/OU=ALL,DC=uch,DC=ac", "user", "pass");

    // set up directory searcher based on default naming context entry
    DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

    // SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
    // subtree = all OU's in the whole domain (can take **LONG** time!)
    ouSearcher.SearchScope = SearchScope.Subtree;
    // ouSearcher.SearchScope = SearchScope.Subtree;

    // define properties to load - here I just get the "OU" attribute, the name of the OU
    ouSearcher.PropertiesToLoad.Add("ou");

    // define filter - only select organizational units
    ouSearcher.Filter = "(objectCategory=organizationalUnit)";

    int cnt = 0;


    foreach (SearchResult deResult in ouSearcher.FindAll())
    {
        string temp = deResult.Properties["ou"][0].ToString();

        strRet += FindSubOU(deResult.Properties["adspath"][0].ToString(), cnt);

    }

    Literal1.Text = strRet;
}


private string FindSubOU(string OU_Path, int cnt)
{
    string strRet = "";

    DirectoryEntry domainRoot = new DirectoryEntry(OU_Path, "user", "pass");

    // set up directory searcher based on default naming context entry
    DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

    // SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
    // subtree = all OU's in the whole domain (can take **LONG** time!)
    ouSearcher.SearchScope = SearchScope.Subtree;
    // ouSearcher.SearchScope = SearchScope.Subtree;

    // define properties to load - here I just get the "OU" attribute, the name of the OU
    ouSearcher.PropertiesToLoad.Add("ou");

    // define filter - only select organizational units
    ouSearcher.Filter = "(objectCategory=organizationalUnit)";

    //adspath
    // do search and iterate over results
    foreach (SearchResult deResult in ouSearcher.FindAll())
    {
        string temp = deResult.Properties["ou"][0].ToString();

        if (!DisplayedOU.Contains(deResult.Properties["ou"][0].ToString()))
        {
            string strPerfix = "";

            for (int i = 0; i < step; i++)
                strPerfix += span;

            strRet += strPerfix + ++cnt + ". " + deResult.Properties["ou"][0].ToString() + " ----> " + deResult.Properties["adspath"][0].ToString() + "<br />";

            DisplayedOU.Add(deResult.Properties["ou"][0].ToString());

            step++;

            strRet += FindSubOU(deResult.Properties["adspath"][0].ToString(), cnt);

            step--;
        }

    }


    return strRet;
}
List DisplayedOU=newlist();
int步长=0;
字符串span=“--”;
私有void getOU2()
{
字符串strRet=“”;
DirectoryEntry domainRoot=new DirectoryEntry(“LDAP://uch.ac/OU=ALL,DC=uch,DC=ac”,“user”,“pass”);
//基于默认命名上下文条目设置目录搜索器
DirectorySearcher USEArcher=新的DirectorySearcher(domainRoot);
//SearchScope:OneLevel=仅直接下属(顶级OU);
//子树=整个域中的所有OU(可能需要**长**时间!)
usearcher.SearchScope=SearchScope.Subtree;
//usearcher.SearchScope=SearchScope.Subtree;
//定义要加载的属性-这里我只得到“OU”属性,即OU的名称
usearcher.PropertiesToLoad.Add(“ou”);
//定义筛选器-仅选择组织单位
usearcher.Filter=“(objectCategory=organizationalUnit)”;
int-cnt=0;
foreach(在usearcher.FindAll()中搜索结果deResult)
{
字符串temp=deResult.Properties[“ou”][0].ToString();
strRet+=FindSubOU(deResult.Properties[“adspath”][0].ToString(),cnt);
}
Literal1.Text=strRet;
}
私有字符串FindSubOU(字符串OU_路径,int cnt)
{
字符串strRet=“”;
DirectoryEntry domainRoot=新的DirectoryEntry(OU_路径,“用户”,“通过”);
//基于默认命名上下文条目设置目录搜索器
DirectorySearcher USEArcher=新的DirectorySearcher(domainRoot);
//SearchScope:OneLevel=仅直接下属(顶级OU);
//子树=整个域中的所有OU(可能需要**长**时间!)
usearcher.SearchScope=SearchScope.Subtree;
//usearcher.SearchScope=SearchScope.Subtree;
//定义要加载的属性-这里我只得到“OU”属性,即OU的名称
usearcher.PropertiesToLoad.Add(“ou”);
//定义筛选器-仅选择组织单位
usearcher.Filter=“(objectCategory=organizationalUnit)”;
//adspath
//搜索并迭代结果
foreach(在usearcher.FindAll()中搜索结果deResult)
{
字符串temp=deResult.Properties[“ou”][0].ToString();
如果(!DisplayedOU.Contains(deResult.Properties[“ou”][0].ToString())
{
字符串strPerfix=“”;
对于(int i=0;i“+deResult.Properties[“adspath”][0]。ToString()+”
”; DisplayedOU.Add(deResult.Properties[“ou”][0].ToString()); step++; strRet+=FindSubOU(deResult.Properties[“adspath”][0].ToString(),cnt); 步骤--; } } 返回strRet; }
杰米提供的代码运行良好。为了回答MacGuyver的问题,为了使用Cast扩展,您需要在代码中包含对System.Linq的引用。我正在使用此代码填充树视图,其中显示我的广告环境中的OU:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            string top = string.Format("LDAP://DC={0}", Domain.GetCurrentDomain().Name.Replace(".", ",DC="));
            ADTree tree = null;

            Task BuildOUStructure = Task.Factory.StartNew(() =>
            {
                tree = new ADTree(top);
            });

            BuildOUStructure.Wait();
            foreach(ADTree t in tree.ChildOUs)
            {
                TreeNode node = new TreeNode(t.RootOU.Path);
                treeView1.Nodes.Add(node);
                if(t.ChildOUs.Count > 0)
                {
                    AddChildren(node, t);
                }
            }
        }

        private void AddChildren(TreeNode parent, ADTree tree)
        {
            foreach(ADTree t in tree.ChildOUs)
            {
                TreeNode node = new TreeNode(t.RootOU.Path);
                parent.Nodes.Add(node);
                if(t.ChildOUs.Count > 0)
                {
                    AddChildren(node, t);
                }
            }
        }
    }

    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);
                        }
                    }
                });
            });
        }
    }
}
使用系统;
使用系统数据;
使用System.Linq;
使用System.Windows.Forms;
使用System.Threading.Tasks;
使用System.DirectoryServices;
使用System.Collections.Generic;
使用System.DirectoryServices.ActiveDirectory;
命名空间WindowsFormsApp8
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
treeView1.Nodes.Clear();
string top=string.Format(“LDAP://DC={0}”,Domain.GetCurrentDomain().Name.Replace(“.”,“,DC=”);
ADTree-tree=null;
Task buildousstructure=Task.Factory.StartNew(()=>
{
树=新的ADTree(顶部);
});
buildousstructure.Wait();
foreach(树中的adt.ChildOUs)
{
TreeNode节点=新的TreeNode(t.RootOU)。
ADTree Root = null;

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

BuildOUStructure.Wait();
List<string> DisplayedOU = new List<string>();
int step = 0;
string span = "<span style='margin-left:6px;'> -- </span>";

private void getOU2()
{
    string strRet = "";
    DirectoryEntry domainRoot = new DirectoryEntry("LDAP://uch.ac/OU=ALL,DC=uch,DC=ac", "user", "pass");

    // set up directory searcher based on default naming context entry
    DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

    // SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
    // subtree = all OU's in the whole domain (can take **LONG** time!)
    ouSearcher.SearchScope = SearchScope.Subtree;
    // ouSearcher.SearchScope = SearchScope.Subtree;

    // define properties to load - here I just get the "OU" attribute, the name of the OU
    ouSearcher.PropertiesToLoad.Add("ou");

    // define filter - only select organizational units
    ouSearcher.Filter = "(objectCategory=organizationalUnit)";

    int cnt = 0;


    foreach (SearchResult deResult in ouSearcher.FindAll())
    {
        string temp = deResult.Properties["ou"][0].ToString();

        strRet += FindSubOU(deResult.Properties["adspath"][0].ToString(), cnt);

    }

    Literal1.Text = strRet;
}


private string FindSubOU(string OU_Path, int cnt)
{
    string strRet = "";

    DirectoryEntry domainRoot = new DirectoryEntry(OU_Path, "user", "pass");

    // set up directory searcher based on default naming context entry
    DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

    // SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
    // subtree = all OU's in the whole domain (can take **LONG** time!)
    ouSearcher.SearchScope = SearchScope.Subtree;
    // ouSearcher.SearchScope = SearchScope.Subtree;

    // define properties to load - here I just get the "OU" attribute, the name of the OU
    ouSearcher.PropertiesToLoad.Add("ou");

    // define filter - only select organizational units
    ouSearcher.Filter = "(objectCategory=organizationalUnit)";

    //adspath
    // do search and iterate over results
    foreach (SearchResult deResult in ouSearcher.FindAll())
    {
        string temp = deResult.Properties["ou"][0].ToString();

        if (!DisplayedOU.Contains(deResult.Properties["ou"][0].ToString()))
        {
            string strPerfix = "";

            for (int i = 0; i < step; i++)
                strPerfix += span;

            strRet += strPerfix + ++cnt + ". " + deResult.Properties["ou"][0].ToString() + " ----> " + deResult.Properties["adspath"][0].ToString() + "<br />";

            DisplayedOU.Add(deResult.Properties["ou"][0].ToString());

            step++;

            strRet += FindSubOU(deResult.Properties["adspath"][0].ToString(), cnt);

            step--;
        }

    }


    return strRet;
}
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            string top = string.Format("LDAP://DC={0}", Domain.GetCurrentDomain().Name.Replace(".", ",DC="));
            ADTree tree = null;

            Task BuildOUStructure = Task.Factory.StartNew(() =>
            {
                tree = new ADTree(top);
            });

            BuildOUStructure.Wait();
            foreach(ADTree t in tree.ChildOUs)
            {
                TreeNode node = new TreeNode(t.RootOU.Path);
                treeView1.Nodes.Add(node);
                if(t.ChildOUs.Count > 0)
                {
                    AddChildren(node, t);
                }
            }
        }

        private void AddChildren(TreeNode parent, ADTree tree)
        {
            foreach(ADTree t in tree.ChildOUs)
            {
                TreeNode node = new TreeNode(t.RootOU.Path);
                parent.Nodes.Add(node);
                if(t.ChildOUs.Count > 0)
                {
                    AddChildren(node, t);
                }
            }
        }
    }

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