简体   繁体   English

使用.Net Core检查目录是否具有读写权限

[英]Checking if a directory has read and write permissions using .Net Core

I am trying to check if a directory has read and write permissions using .Net Core. 我正在尝试检查目录是否具有使用.Net Core的读写权限。

I am using Visual Studio 2019, .Net Core 2.1. 我正在使用Visual Studio 2019,.Net Core 2.1。 I have tried GetAccessControl with no luck, so tried the following. 我没有运气就尝试过GetAccessControl,因此尝试了以下方法。

public static bool DirectoryHasPermission(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath))
    {
        return false;
    }

    FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, DirectoryPath);
    f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");

    try
    {
        f2.Demand();
    }
    catch (SecurityException s)
    {
        Console.WriteLine(s.Message);
        return false;
    }

    return true;
}

No matter what directory path I put in, even if it doesn't exist it returns true. 无论我输入什么目录路径,即使它不存在,它也会返回true。

FileIOPermission is part of .NET's code security - it's meant to allow you to host .NET code that has lower permissions than the host process (ie software process isolation). FileIOPermission是.NET代码安全性的一部分-允许您承载权限比主机进程低(即软件进程隔离)的.NET代码。 It doesn't have anything to do with the file system's access rights. 它与文件系统的访问权限无关。

For .NET Core, you can read and modify access control to files with the System.IO.FileSystem.AccessControl package. 对于.NET Core,可以使用System.IO.FileSystem.AccessControl包读取和修改对文件的访问控制。 After adding the package, you can do something like this: 添加软件包后,您可以执行以下操作:

using System.IO;

public void Main(string[] args)
{
  var ac = new FileInfo(@"C:\Test.txt").GetAccessControl();

  // ac has the ACL for the file
}

Needless to say, this is Windows specific. 不用说,这是Windows特定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM