【问题标题】:Check file Permission in C# .NET Core在 C# .NET Core 中检查文件权限
【发布时间】:2020-06-27 09:54:42
【问题描述】:

我正在做一个项目,我必须对文件执行完整性检查。我需要确保当前系统用户对文件具有读取权限,我首先尝试使用:

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 似乎大部分已被弃用,所以这似乎也是一个死胡同。有没有其他方法可以告诉用户对文件有什么权限?

【问题讨论】:

  • 你的意思是它不起作用 - 没有抛出异常但你无权访问?
  • @RicardoPeres 完全正确。
  • @TomTom 询问如何检查文件是否可读并不是题外话......
  • 可能重复 stackoverflow.com/questions/21623343 :您不能依赖此方法的结果。似乎除了尝试以所需的访问权限打开文件之外别无他法。
  • @Clint 不幸的是,由于整个电晕情况,我会尽快(在接下来的 24 小时内),我的工作日非常忙碌,atm。不过,我会在尝试后立即通知您,非常感谢您

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


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

片段:检查 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

【讨论】:

  • 你好。可悲的是,这对我不起作用,即因为,显然我应该首先提到这一点:服务器运行在 Linux 上,而不是 Windows。所以当我运行你的代码时,我得到了:Unhandled exception. System.PlatformNotSupportedException: Access Control List (ACL) APIs are part of resource management on Windows and are not supported on this platform.
  • @rasmus91,啊,真是太糟糕了,哈哈。 check this out
  • 非常感谢。我不太确定我是否应该接受你的回答(如果你说它有效,它可能有效)但我不能在我们的环境中完全使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 2010-11-19
  • 2015-02-10
相关资源
最近更新 更多