无法从OU中获取用户

本文关键字:获取 用户 OU | 更新日期: 2023-09-27 18:12:09

我正在做一个项目,我必须从活动目录中的特定OU中获取用户。

我使用Dropdown菜单来存储当前的所有ou。一旦用户选择了一个特定的OU并单击按钮,该OU的可用用户就会显示在文本框中。

这是正在使用的代码:

public MainWindow()
    {
        InitializeComponent();
        DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
        string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();
        DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);
        DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);
        ouSearcher.SearchScope = SearchScope.Subtree;
        ouSearcher.PropertiesToLoad.Add("ou");
        ouSearcher.PropertiesToLoad.Add("cn");
        ouSearcher.SearchScope = SearchScope.Subtree;
        ouSearcher.Filter = "(objectCategory=organizationalUnit)";
        try
        {
            comboBox1.SelectedIndex = 0;
            comboBox1.Items.Insert(0, "Select An OU");
            string ouName;
            foreach (SearchResult deResult in ouSearcher.FindAll())
            {
                ArrayList alObjects = new ArrayList();
                ouName = deResult.Properties["ou"][0].ToString();
                comboBox1.Items.Insert(1, ouName.ToString());
            }          
        }
        catch (Exception ex2)
        {
        }
    }
private void button1_Click(object sender, RoutedEventArgs e) //Error is present in this part
    {
        string selectou = comboBox1.SelectedValue.ToString();
        DirectoryEntry rootDSE = new DirectoryEntry("LDAP://" + selectou);
        string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString(); //Here is the problem
        DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + selectou);
        DirectorySearcher ouSearcher = new DirectorySearcher(selectou);
        ouSearcher.SearchScope = SearchScope.Subtree;
        ouSearcher.PropertiesToLoad.Add("cn");
        ouSearcher.SearchScope = SearchScope.Subtree;
        ouSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
        foreach (SearchResult deResult in ouSearcher.FindAll())
        {
            ArrayList alObjects = new ArrayList();
            string dcName = deResult.Properties["cn"][0].ToString();
            textBox1.Text = textBox1.Text + dcName.ToString() + "'n";
        }
    }

现在问题发生在button1_click函数。对于defaultcontext,它抛出以下错误:

System.Runtime.InteropServices.COMException: The server is not operational.

我不知道如何处理这个错误。我是不是错过了什么集会?

无法从OU中获取用户

改变这一行

ouName = deResult.Properties["ou"][0].ToString();

ouName = deResult.Properties["distinguishedName"][0].ToString();

我想你会没事的