Hiện tại, không có API tích hợp trong .NET Core cho việc này. Tuy nhiên, nhóm .NET Core đang làm việc để làm cho Mono.Posix
khả dụng trên .NET Core. Điều này cho thấy API để thực hiện loại hoạt động này trong mã được quản lý. Xem https://github.com/dotnet/corefx/issues/15289 và https://github.com/dotnet/corefx/issues/3186. Bạn có thể thử một phiên bản sớm của API này ở đây: 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;
Nếu bạn không muốn sử dụng Mono.Posix, bạn có thể thực hiện chức năng này tương tự bằng cách gọi mã gốc. Sử dụng P/Invoke, bạn có thể gọi hàm chmod
từ libc
. Xem man 2 chmod
để biết thêm chi tiết về API gốc.
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));
}
}
Microsoft sử dụng mô hình cấp phép tệp của họ trên Windows và dịch nó sang Linux/UNIX. Vì vậy, lệnh gọi 'chmod' là nội bộ, https://github.com/dotnet/corefx/blob/bffef76f6af208e2042a2f27bc081ee908bb390b/src/Common/src/Interop/Unix/System.Native/Interop.ChMod.cs và chỉ được sử dụng trong https://github.com/dotnet/corefx/blob/801dde95a5eac06140d0ac633ac3f9bfdd25aca5/src/System.IO.FileSystem/src/System/IO/FileSystemInfo.Unix.cs Vì vậy, trong trường hợp của bạn, bạn phải dịch 644 sang quyền tệp Windows tương ứng và sau đó sử dụng cách Windows để thao tác tệp. –