0

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

我使用Dropdown菜单来存储所有存在的 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 函数上。对于默认上下文,它会引发以下错误:

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

我无法弄清楚如何解决这个错误。我错过了某种程序集吗?

4

1 回答 1

0

更改此行

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

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

我想你会没事的

于 2014-07-08T16:15:21.173 回答