我正在开发一个项目,必须对文件执行健全性检查。我需要确保当前系统用户具有该文件的读取权限,我首先尝试这样做:
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
关于c# - 检查 C# .NET Core 中的文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60703387/