我正在编写我的第一个代码来读取 AD 组的所有成员,但没有获得正确数量的组成员:
public static void GetListOfAdUsersByGroup (string domainName, string groupName) {
PrincipalContext ctx = new PrincipalContext (ContextType.Domain); // Set up the domain context
GroupPrincipal group = GroupPrincipal.FindByIdentity (ctx, groupName); // Find the specified group
if (group != null) {
foreach (Principal p in group.GetMembers()) {
Console.WriteLine ("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
}
}
}
我已经有问题了。group.Members.Count 是 3,我打印这 3 个成员,但数字应该大得多。我这么早就做错了什么?
编辑:在列出我的 3 个用户之前,我在输出窗口中收到两个错误。错误是:
抛出异常:mscorlib.dll 中的“System.ArgumentException”异常抛出:mscorlib.dll 中的“System.FormatException”
编辑2:
我基本上从其他地方窃取了以下代码,并且还从该代码中获得了 3 个结果!
public static IEnumerable<string> GetGroupMemberList (GroupPrincipal group, bool recursive = false) {
using (var memberPrincipals = group.GetMembers(recursive)) {
foreach (Principal member in memberPrincipals) {
yield return member.SamAccountName;
}
}
}
像这样调用:
PrincipalContext ctx = new PrincipalContext (ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity (ctx, "DOC.WKCC");
_elements = new List<string>(GetGroupMemberList (group, true));