如何在 C# 中显示来自活动目录的搜索结果集合的值?



我的老板给我发了一个带有一些ID号的txt文件。我需要从拥有这些 ID 号的用户那里获取一些信息。

我从来没有用Active Directory做过任何事情,所以我有点迷茫。现在,我只是想确保我可以从 AD 访问"muID"属性。但是当我在AD中搜索该属性并尝试获取该属性的值时,我得到了它的输出"System.DirectoryServices.ResultPropertyValueCollection"而不是值,该值应类似于"111123456"。

这是我到目前为止的代码:

SearchResultCollection sResults = null;
string path = "LDAP://muad1";
DirectoryEntry dEntry = new DirectoryEntry(path);
DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
dSearcher.Filter = "(&(objectClass=user))";
dSearcher.PropertiesToLoad.Add("muID");
SearchResultCollection results = dSearcher.FindAll();
if (results != null)
{
foreach (SearchResult result in results)
{                    
Console.WriteLine(result.ToString());
}
}

但这行不通。我试过四处搜索,但我找不到任何有用的东西。我试过这个

Console.WriteLine(result.Properties["muID"].ToString());
Console.WriteLine(dEntry.Properties[result].ToString());
Console.WriteLine(dEntry.Properties[result][0].ToString());
Console.WriteLine(dEntry.Properties["result"].ToString());

但它们都不起作用。它们要么抛出错误,要么执行与代码块上的错误相同的操作。

同样,我想确保我正在访问该属性,以便我可以获取所需的信息。我认为显示属性的值将是一个很好的检查方法。但它没有显示正确的东西。

哦,我觉得你们离得很近。

SearchResultCollection包含SearchResult实例: 搜索结果集合上的信息

SearchResult包含Properties属性:搜索结果上的信息

SearchResultProperties是一个ResultPropertyCollection:关于结果属性集合的信息

如果您从

Console.WriteLine(result.ToString());

自:

Console.WriteLine(result.Properties["muID"][0].ToString());

然后你应该找到你要找的东西。为了安全起见,我还确保在访问 [0] 处的元素之前,您先检查以确保它存在。如果用户根本没有该属性,则可能会遇到异常。

编辑: 这可能有助于您查看哪些属性和值对可供您使用。如果您在任何地方都看不到"muID",那么这就是您收到错误的原因。

if (results != null)
{
foreach (SearchResult result in results)
{                    
foreach(string propName in result.Properties.PropertyNames)
{
foreach(object myCollection in result.Properties[propName])
{
Console.WriteLine(propName + " : " + myCollection.ToString());
}
}
}
}

最新更新