[英]Query Active Directory in C#
I am trying to perform a query to Active Directory to obtain all the first names of every user. 我正在尝试对Active Directory执行查询,以获取每个用户的所有名字。 So I have created a new console application and in my main method have the following code: 因此,我创建了一个新的控制台应用程序,并且在我的主要方法中具有以下代码:
try
{
DirectoryEntry myLdapConnection =new DirectoryEntry("virtual.local");
myLdapConnection.Path = "LDAP://DC=virtual,DC=local";
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.PropertiesToLoad.Add("cn");
SearchResultCollection allUsers = search.FindAll();
I have added some code to check that the connection is being made and that the path can be found. 我添加了一些代码来检查是否建立了连接并可以找到路径。 I also ensure that the Collection is not empty. 我还确保Collection不为空。
//For Debugging
if(DirectoryEntry.Exists(myLdapConnection.Path())
{
Console.WriteLine("Found");
}
else Console.WriteLine("Could Not Find LDAP Connection");
//In my case prints 230
Console.WriteLine("Total Count: " + allUsers.Count);
foreach(SearchResult result in allUsers)
{
//This prints out 0 then 1
Console.WriteLine("Count: " + result.Properties["cn'].Count);
if (result.Properties["cn"].Count > 0) //Skips the first value
{
Console.WriteLine(String.Format("{0,-20} : {1}",
result.Properties["cn"][0].ToString())); //Always fails
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
I have specified in the code, where it prints out the properties, that it always fails. 我在代码中指定了它打印出属性的位置,但它总是失败。 I get a System.FormatException being caught here that states the Index must be greater than zero and less than the size of the argument list. 我在这里遇到一个System.FormatException,该异常指出Index必须大于零且小于参数列表的大小。
So in the end I'm not really sure how "result.Properties" works and was wondering if you had any advise on how to fix or troubleshoot the problem. 因此,最后我不确定“ result.Properties”如何工作,并且想知道您是否对如何解决或解决问题有任何建议。
您正在定义两个格式说明符{0}和{1},但仅指定一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.