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

C# .NET 5提示File无GetAccessControl定义 如何获取文件创建者

错误原因

File.GetAccessControl 属于Windows平台专属的访问控制API,.NET 5及以上版本没有默认集成该方法,相关实现被拆分到了独立的NuGet包中,因此直接调用会触发编译错误。

解决办法

方案1:安装独立NuGet包兼容原有代码

  • 打开项目的NuGet包管理界面,搜索并安装 System.IO.FileSystem.AccessControl
  • 安装完成后原有代码即可正常编译,你可以补充异常处理提升鲁棒性:
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

// 调用示例
public string GetFileOwner(string filePath)
{
    if (!File.Exists(filePath))
        return string.Empty;
    try
    {
        var fileAcl = File.GetAccessControl(filePath);
        var ownerAccount = fileAcl.GetOwner(typeof(NTAccount));
        return ownerAccount?.ToString() ?? string.Empty;
    }
    catch (UnauthorizedAccessException)
    {
        // 无权限访问目标文件的ACL
        return "无权限获取";
    }
}

注意:该方案仅支持Windows平台运行,符合你当前Windows Forms项目的场景,如果需要兼容跨平台场景可参考方案2

方案2:调用Windows原生API实现(无需额外NuGet包)

如果你不想引入额外的第三方包,可以直接调用Windows底层的GetFileSecurity API实现,示例代码如下:

using System.Runtime.InteropServices;
using System.Security.Principal;

public class FileOwnerHelper
{
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool GetFileSecurity(string lpFileName, int dwRequestedInformation, byte[] lpSecurityDescriptor, int nLength, out int lpnLengthNeeded);

    private const int OWNER_SECURITY_INFORMATION = 0x00000001;

    public static string GetFileOwner(string filePath)
    {
        if (!File.Exists(filePath))
            return string.Empty;
        int bufferSize = 0;
        GetFileSecurity(filePath, OWNER_SECURITY_INFORMATION, null, 0, out bufferSize);
        if (bufferSize == 0)
            return string.Empty;
        byte[] buffer = new byte[bufferSize];
        if (!GetFileSecurity(filePath, OWNER_SECURITY_INFORMATION, buffer, bufferSize, out _))
            return string.Empty;
        var sid = new SecurityIdentifier(buffer, 0);
        return sid.Translate(typeof(NTAccount))?.ToString() ?? string.Empty;
    }
}

这个方案仅依赖Windows系统自带的API,无需安装额外NuGet包,同样仅支持Windows平台运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:30:05