我的老板向我发送了一个包含一些 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());
但它们都不起作用。它们要么抛出错误,要么执行与代码块上的错误相同的操作。
再次,我想确保我正在访问该属性,以便我可以获得我想要的信息。我认为显示财产的价值是一个很好的检查方法。但它没有显示正确的东西。
哦,我感觉你很亲近。
A
SearchResultCollection
包含 SearchResult
实例:有关 SearchResultCollection 的信息
A
SearchResult
包含 Properties
属性:SearchResult 信息
SearchResult
Properties
是一个 ResultPropertyCollection
:有关 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());
}
}
}
}