You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#操作Active Directory:获取指定组所有成员仅返回单个用户问题

问题排查与修正

嘿,我一眼就发现问题所在啦——你把Console.ReadLine()放在foreach循环内部了!每次输出一个用户的信息后,程序就会停在这里等待你按下回车键才会继续执行下一次循环,所以你才会误以为只返回了单个用户。

修正后的代码

static void Main(string[] args) { GetNestedGroupName("Groupname"); }
public static void GetNestedGroupName(string groupName) {
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "ad.domain.com")) {
        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName)) {
            if (group != null) {
                // 如果你需要包含嵌套组的成员,把GetMembers()改成GetMembers(true)
                foreach (Principal p in group.GetMembers()) {
                    Console.WriteLine("name: " + p.SamAccountName);
                }
                // 将等待输入的代码移到循环外,等所有成员输出完毕再暂停
                Console.ReadLine();
            } else {
                Console.WriteLine("nothing");
                Console.ReadLine();
            }
        }
    }
}

额外说明

  • 关于GetMembers()方法:默认的无参版本只会返回当前组的直接成员,如果你的组里包含其他子组,并且需要获取这些子组里的用户,记得传入true参数启用递归遍历,也就是group.GetMembers(true)。
  • 关于Console.ReadLine():把它放在循环外后,程序会一次性输出所有组成员的信息,之后才会等待你按下回车键结束程序,这样你就能看到完整的成员列表了。

内容的提问来源于stack exchange,提问作者user3091744

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:27:45