我正在尝试学习如何使用 .NET Core 在 Linux/Unix 上设置文件权限。我已经在这里发现了一个问题,它指出了 System.IO.FileSystem 的方向,但我似乎找不到任何有关如何使用它的文档。
简而言之,我想从仅在 Linux 上运行的 .NET Core 应用程序 chmod 文件 644,但不知道如何继续。
目前,.NET Core 中没有为此构建的 API。然而,.NET Core 团队正在努力使Mono.Posix
可在 .NET Core 上使用。这公开了 API 以在托管代码中执行此类操作。看https://github.com/dotnet/corefx/issues/15289 https://github.com/dotnet/corefx/issues/15289 and https://github.com/dotnet/corefx/issues/3186 https://github.com/dotnet/corefx/issues/3186。您可以在此处尝试此 API 的早期版本:https://www.nuget.org/packages/Mono.Posix.NETStandard/1.0.0-beta1 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,您可以通过调用本机代码来实现相同的功能。使用 P/Invoke,您可以调用chmod
函数来自libc
. See man 2 chmod
有关本机 API 的更多详细信息。
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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)