【问题标题】:Check access permisions in C# - "on Linux"检查 C# 中的访问权限 - “在 Linux 上”
【发布时间】:2018-08-31 23:24:17
【问题描述】:

我想知道在使用 C# 时如何检查 Linux 系统上文件和目录的访问权限。

我想知道我是否会读、写或执行。

System.IO.Directory.GetAccessControl() 在 Linux 上不起作用。

Unhandled Exception: System.PlatformNotSupportedExcpetion: Operation is not supported on this platform.

跟踪开始于:System.Security.AccessControl.NativeObjectSecurity.InternalGet

我尝试使用的方法:

static bool HasDirectoryPermission(FileSystemRights right, string path) {
   var allowed = false;
   var denied = false;
   var accessControlList = System.IO.Directory.GetAccessControl(path);
   if (accessControlList == null)
      return false;
   var accessRules = accessControlList.GetAccessRules(true, true,
                                 typeof(System.Security.Principal.SecurityIdentifier));
   if (accessRules == null)
      return false;

   foreach (FileSystemAccessRule rule in accessRules) {
      if ((right & rule.FileSystemRights) != right)
         continue;

      if (rule.AccessControlType == AccessControlType.Allow)
         allowed = true;
      else if (rule.AccessControlType == AccessControlType.Deny)
         denied = true;
   }

   return (allowed && !denied);
}

文件路径的方法几乎相同。

【问题讨论】:

  • 也许这个答案会有所帮助。 stackoverflow.com/a/41019841/758848
  • 天哪。我希望theres另一个解决方案..安装包后:i.imgur.com/1dy92CS.png
  • 在使用框架 4.7 时,我不需要安装任何额外的包......但是我想使用更低的东西。喜欢 4.5
  • Linux 上仅正式支持 .NET Core,因此您的“我想使用 4.5 之类的更低版本”的声明根本无效。
  • 没有。这不起作用。仍然以同样的例外告终。我真的不知道如何诚实地使用它。它向DirectoryInfo 添加了一些扩展方法,但即使没有这个包,我也可以访问这些方法。

标签: c# linux permissions


【解决方案1】:

我自己想出了一个有点“肮脏”的解决方案。

  • 我从重定向输出开始 bash
  • 传递ls -l + 文件或目录的路径作为参数
  • 找到以文件名或目录名结尾的行
  • 最后我检查该行的第 2/3/4 个字符是否为 r/w/x

https://pastebin.com/1PQNaB1m

【讨论】:

  • 将第 45 行替换为 string cmd = "ls -l \"" + p + "\""; 以使其适用于包含空格的路径
猜你喜欢
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2013-09-14
  • 2015-01-11
相关资源
最近更新 更多