gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:43:27 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com