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

如何在Windows及Windows Server中获取所有用户以管理文件夹权限

获取Windows/Windows Server全量用户账户(含本地、内置、系统账户)

你的现有代码仅能读取目标文件夹已配置权限的账户,要获取系统中所有符合格式的账户,可通过以下C#实现:

1. 读取本地用户与本地组账户

使用System.DirectoryServices.AccountManagement命名空间,可便捷枚举本地机器的用户和组(包括BUILTIN内置组):

using System.DirectoryServices.AccountManagement;
using System.Collections.Generic;

// 初始化HashSet存储账户,自动去重
var allAccounts = new HashSet<string>();

// 获取本地机器上下文
using (var machineContext = new PrincipalContext(ContextType.Machine))
{
    // 枚举所有本地用户
    using (var userPrincipal = new UserPrincipal(machineContext))
    using (var searcher = new PrincipalSearcher(userPrincipal))
    {
        foreach (var principal in searcher.FindAll())
        {
            if (principal is UserPrincipal user)
            {
                allAccounts.Add($"{machineContext.Name}\\{user.SamAccountName}");
            }
        }
    }

    // 枚举所有本地组(含BUILTIN组)
    using (var groupPrincipal = new GroupPrincipal(machineContext))
    using (var searcher = new PrincipalSearcher(groupPrincipal))
    {
        foreach (var principal in searcher.FindAll())
        {
            if (principal is GroupPrincipal group)
            {
                allAccounts.Add($"{machineContext.Name}\\{group.SamAccountName}");
            }
        }
    }
}

2. 添加NT AUTHORITY特殊系统账户

NT AUTHORITY\SYSTEM、NT AUTHORITY\NETWORK SERVICE这类特殊账户,可通过SecurityIdentifier结合WellKnownSID类型获取:

using System.Security.Principal;

// 定义需枚举的特殊系统账户SID类型
var wellKnownSidTypes = new[]
{
    WellKnownSidType.LocalSystemSid,
    WellKnownSidType.NetworkServiceSid,
    WellKnownSidType.LocalServiceSid,
    WellKnownSidType.AuthenticatedUserSid,
    WellKnownSidType.EveryoneSid
};

foreach (var sidType in wellKnownSidTypes)
{
    var sid = new SecurityIdentifier(sidType, null);
    allAccounts.Add(sid.Translate(typeof(NTAccount)).Value);
}

3. 加载到列表控件

将去重后的所有账户添加到你的列表中:

Control.Instance.listb1.Items.Clear();
foreach (var account in allAccounts)
{
    Control.Instance.listb1.Items.Add(account);
}

注意事项

  • 需在项目中添加System.DirectoryServices.AccountManagement程序集引用;
  • 程序需以管理员权限运行,否则可能无法读取部分系统级账户或组;
  • 若需获取域环境下的域用户/组,将ContextType.Machine替换为ContextType.Domain并指定对应域名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:07:49