我正在开发一个项目,我必须从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功能上。对于defaultcontext,它会引发以下错误:
System.Runtime.InteropServices.COMException: The server is not operational.
我无法弄清楚如何解决这个错误。我错过了某种装配吗?
答案 0 :(得分:0)
更改此行
ouName = deResult.Properties["ou"][0].ToString();
到
ouName = deResult.Properties["distinguishedName"][0].ToString();
我想你会没事的