我需要一个根 AD 组,并且需要枚举其所有子组。我有一个代码,它连接到 AD 服务器并尝试检索子组列表。
这是代码:
private IEnumerable<SearchResult> GetSubGroups(string groupId)
{
using (var searcher = new DirectorySearcher(new DirectoryEntry(adServerName, adLogin, adPassword)))
{
searcher.Filter = string.Format("(&(objectClass=group)({0}))", groupId);
//Get the Root Group
var result = searcher.FindOne();
object resultMembers = result.GetDirectoryEntry().Invoke("Members", null);
foreach(var member in ((IEnumerable) resultMembers))
{
var memberEntry = new DirectoryEntry(member);
var subgroupsSearcher = new DirectorySearcher(memberEntry);
subgroupsSearcher.Filter = "(objectClass=group)";
subgroupsSearcher.PropertiesToLoad.Add("samaccountname");
subgroupsSearcher.PropertiesToLoad.Add("name");
var foundSubGroupResult = subgroupsSearcher.FindOne();
...
}
return new List<SearchResult> {result};
}
}
枚举 Invoke("Members", null) 结果时,我为每个结果创建另一个 DirectoryEntry。问题是,当 asubgroupSearcher.FindOne()
被调用时,它以 a 结尾DirectoryServicesCOMException
。
Here's the exception stack trace:
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
...other methods...
异常的消息属性说:"An operations error occured"
我已经记录了错误代码,它是-2147016672
在从子组对象创建 DirectoryEntry 时,我还尝试隐式初始化 UserName 属性:
foreach(var member in ((IEnumerable) resultMembers))
{
var memberEntry = new DirectoryEntry(member);
memberEntry.Username = adLogin;
var subgroupsSearcher = new DirectorySearcher(memberEntry)
...
}
但它给出了相同的结果。
我做错了什么?任何帮助都是可观的。