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

C#控制台程序:获取当前用户AD组并生成TXT文件

嘿,你已经找对方向了!我来帮你把这段代码补全并优化,确保能顺利获取AD用户组列表并写入指定的TXT文件。

完整实现代码

首先确保你的项目引用了System.DirectoryServices和System.DirectoryServices.AccountManagement程序集,然后用下面的完整代码:

using System;
using System.DirectoryServices.AccountManagement;
using System.IO;

class ADGroupExporter
{
    static void Main()
    {
        try
        {
            // 替换为你的实际域名,比如"contoso.com"
            string domain = "<Domain>";
            // 要查询的用户名,换成Environment.UserName可获取当前登录用户
            string targetUser = "<UserName>";
            // 替换为你要保存文件的完整路径,比如@"C:\Logs\UserADGroups.txt"
            string outputFilePath = @"<OutputFilePath>";

            // 建立与AD域的连接上下文
            using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
            {
                // 根据SAM账户名查找目标用户
                UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, targetUser);

                if (user != null)
                {
                    // 写入文件操作,自动处理流的释放
                    using (var writer = new StreamWriter(outputFilePath))
                    {
                        writer.WriteLine($"用户 {targetUser} 的AD组列表:");
                        writer.WriteLine("====================================");

                        // 遍历用户所属的所有AD组
                        foreach (GroupPrincipal group in user.GetGroups())
                        {
                            writer.WriteLine(group.Name);
                            // 手动释放GroupPrincipal资源,避免内存泄漏
                            group.Dispose();
                        }
                    }

                    Console.WriteLine($"成功导出!文件路径:{outputFilePath}");
                }
                else
                {
                    Console.WriteLine($"未找到用户:{targetUser}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"出错了:{ex.Message}");
        }
    }
}
几个关键提示
  • 动态获取当前用户:如果不需要指定固定用户名,把targetUser改成Environment.UserName,程序会自动获取当前运行者的账户名。
  • 权限注意事项:运行程序的用户需要有读取AD用户组信息的权限,不然会抛出权限不足的异常。
  • 组范围选择:代码里用的GetGroups()会返回用户直接和间接所属的所有组;如果需要获取包含权限相关的安全组(含嵌套组),可以换成GetAuthorizationGroups()方法。
  • 资源释放:遍历组的时候记得调用group.Dispose(),避免未释放的资源占用内存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:23:07