c# - 检查 C# .NET Core 中的文件权限

标签 c# .net-core file-permissions .net-core-3.1

我正在开发一个项目,必须对文件执行健全性检查。我需要确保当前系统用户具有该文件的读取权限,我首先尝试这样做:

var readPermission = new FileIOPermission(FileIOPermissionAccess.Read, filePath);

try
{
    readPermission.Demand();
}
catch (SecurityException ex)
{
    //handle the exception, which should be thrown if current user does NOT have the read permission
}

这不起作用,例如没有抛出异常,所以我尝试这样做:

var readPermission = new FileIOPermission(FileIOPermissionAccess.Read, filePath);


if(! SecurityManager.IsGranted(readPermission))
{

    throw new SecurityException(
        String.Format("System user: {0} does not have read access to file {1}", User.Identity.Name, filePath)
        );
}
然而,SecurityManager api 似乎大部分已被弃用,因此这似乎也是一个死胡同。是否有其他方法可以告诉用户对文件拥有哪些权限?

最佳答案

  • 首先,获取当前 FileInfo 对象描述的文件的访问控制列表 (ACL) 条目,该条目封装在 FileSecurity 对象中
  • 然后,我们使用 GetAccessRules 获取与上述 FileSecurity 对象关联的规则集合
  • 规则集合表示 FileSystemAccessRule 派生自的 AuthorizationRule 对象,您可以查询该对象以了解与文件相关的权限

代码片段:检查 test.txt 是否具有读取权限(已使用 .Net Core 进行测试)

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

var MyPath = @"C:\Users\repos\test.txt";
var fInfo = new FileInfo(MyPath);

FileSecurity fSecurity = fInfo.GetAccessControl();

SecurityIdentifier usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
FileSystemRights fileRights = FileSystemRights.Read | FileSystemRights.Synchronize; //All read only file usually have Synchronize added automatically when allowing access, refer the msdn doc link below

var rules = fSecurity.GetAccessRules(true, true, usersSid.GetType()).OfType<FileSystemAccessRule>();
var hasRights = rules.Where(r => r.FileSystemRights == fileRights).Any();

Nuget 先决条件:System.IO.FileSystem.AccessControl

引用:FileSystemRights Enums

关于c# - 检查 C# .NET Core 中的文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60703387/

相关文章:

c# - 如何捕获 ExtendedSocketException?

android - 在 android 11(sdk 30) 中,如何从下载文件夹上传 pdf 文件?我收到权限被拒绝的 EACCES 消息

java - 更改文件夹中文件的文件权限

c# - 如何将通过反射获得的对象传递给模板?

c# - 新的 HttpConfiguration(); Nunit 失败但 MsTests 失败

c# - 在代码中获取版本号.Net Core 3 WPF Sideload

asp.net-core - dotnet publish -o ./dist 不在 msbuild 中设置 $OutDir 或 $OutPath

python - 使用 Python 的 tarfile 创建 tarball 时保留文件权限

c# - 添加到 xmlnode 的未命名命名空间

c# - 位图到 avi 文件 c# .Net