c# - 使用 .NET Core 的 Linux/Unix 上的文件权限

标签 c# .net asp.net-core .net-core

我正在尝试学习如何使用 .NET Core 在 Linux/Unix 上设置文件权限。我已经在这里找到了一个问题,它指出了 System.IO.FileSystem 的方向,但我似乎找不到任何关于如何使用它的文档。

简而言之,我想从仅在 Linux 上运行的 .NET Core 应用程序中对文件 644 进行 chmod,但我不知道如何继续。

最佳答案

目前,.NET Core 中没有为此内置的 API。但是,.NET Core 团队正在努力使 Mono.Posix 在 .NET Core 上可用。这会公开 API 以在托管代码中执行此类操作。参见 https://github.com/dotnet/corefx/issues/15289https://github.com/dotnet/corefx/issues/3186 .您可以在此处试用此 API 的早期版本:https://www.nuget.org/packages/Mono.Posix.NETStandard/1.0.0-beta1

    var unixFileInfo = new Mono.Unix.UnixFileInfo("test.txt");
    // set file permission to 644
    unixFileInfo.FileAccessPermissions =
        FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite
        | FileAccessPermissions.GroupRead
        | FileAccessPermissions.OtherRead;

如果您不想使用 Mono.Posix,您可以通过调用 native 代码来实现相同的功能。使用 P/Invoke,您可以从 libc 调用 chmod 函数。有关 native API 的更多详细信息,请参见 man 2 chmod

using System;
using System.IO;
using System.Runtime.InteropServices;
using static System.Console;

class Program
{
    [DllImport("libc", SetLastError = true)]
    private static extern int chmod(string pathname, int mode);

    // user permissions
    const int S_IRUSR = 0x100;
    const int S_IWUSR = 0x80;
    const int S_IXUSR = 0x40;

    // group permission
    const int S_IRGRP = 0x20;
    const int S_IWGRP = 0x10;
    const int S_IXGRP = 0x8;

    // other permissions
    const int S_IROTH = 0x4;
    const int S_IWOTH = 0x2;
    const int S_IXOTH = 0x1;

    static void Main(string[] args)
    {
        WriteLine("Setting permissions to 0755 on test.sh");
        const int _0755 =
            S_IRUSR | S_IXUSR | S_IWUSR
            | S_IRGRP | S_IXGRP
            | S_IROTH | S_IXOTH;
        WriteLine("Result = " + chmod(Path.GetFullPath("test.sh"), (int)_0755));

        WriteLine("Setting permissions to 0644 on sample.txt");
        const int _0644 =
            S_IRUSR | S_IWUSR
            | S_IRGRP
            | S_IROTH;
        WriteLine("Result = " + chmod(Path.GetFullPath("sample.txt"), _0644));

        WriteLine("Setting permissions to 0600 on secret.txt");
        const int _0600 = S_IRUSR | S_IWUSR;
        WriteLine("Result = " + chmod(Path.GetFullPath("secret.txt"), _0600));
    }
}

关于c# - 使用 .NET Core 的 Linux/Unix 上的文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132081/

相关文章:

c# - Linq 检查 where 子句中的百分比

c# - 如何始终调用C#类的最新字段

c# - 应用程序在基于 .NET 的 COM 对象的 CoCreateInstance 期间挂起

asp.net - Web 服务的小型性能测试

asp.net-core - Razor 页面中的流利验证

asp.net-core - DDD 通过多层过滤器

c# - 在 ASP.NET MVC 中获取 DateTime.UtcNow 有多难?

c# - 反序列化一个未命名的数组

c# - 尝试播放流中的声音;文件以.mp3开头,然后是byte []数组,然后是流。.为什么它不起作用?

c# - 为 prod 和 dev 指定 asp.net core 1.0 WebAPI.exe 应该在 program.cs 中使用的 url(端口)