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

.NET 6类库中获取拥有文件读取权限的域用户组方案

获取拥有文件读取权限的域用户组(.NET 6 兼容实现)

原代码在.NET 6类库中无法运行,原因是File.GetAccessControl属于Windows平台专属API,若类库目标框架为通用跨平台的net6.0,则无法直接调用。以下是适配.NET 6的实现方案:

前提条件

  • 若类库需跨平台但仅在Windows环境运行,需在项目文件中添加Windows平台支持:
<PropertyGroup>
  <TargetFramework>net6.0</TargetFramework>
  <SupportedOSPlatforms>windows</SupportedOSPlatforms>
</PropertyGroup>
  • 或直接将目标框架设为Windows专属:net6.0-windows
  • 确保项目引用System.Security.AccessControl NuGet包(若未自动包含)

实现代码

using System.Collections.Generic;
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;
using System.Linq;

public List<string> GetFileReadGroups(string filePath)
{
    var fileSecurity = new FileInfo(filePath).GetAccessControl();
    var readRules = fileSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
    var groups = new List<string>();

    foreach (FileSystemAccessRule rule in readRules)
    {
        // 检查是否包含读取数据权限,同时仅保留允许规则
        if ((rule.FileSystemRights & FileSystemRights.ReadData) == FileSystemRights.ReadData 
            && rule.AccessControlType == AccessControlType.Allow)
        {
            if (rule.IdentityReference is SecurityIdentifier sid)
            {
                try
                {
                    var account = (NTAccount)sid.Translate(typeof(NTAccount));
                    // 筛选域用户组(格式通常为 域名\组名)
                    if (account.Value.Contains("\\"))
                    {
                        groups.Add(account.Value);
                    }
                }
                catch (IdentityNotMappedException)
                {
                    // 跳过无法映射的SID,可按需添加日志记录逻辑
                    continue;
                }
            }
        }
    }

    // 去重后返回结果
    return groups.Distinct().ToList();
}

关键说明

  • 用FileInfo.GetAccessControl替代File.GetAccessControl,功能一致且平台兼容性处理更灵活
  • 增加AccessControlType.Allow判断,避免误将拒绝读取权限的规则纳入结果
  • 捕获IdentityNotMappedException,防止无法解析的SID导致程序崩溃
  • 对结果去重,避免重复的组名
  • 通过账户名称格式(含\)筛选域用户组,排除本地组或非域账户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:25:20