我想在C#中将文件的权限设置为“不能删除”,只允许读取。但是我不知道如何实现。你能帮助我吗?
这是关于属性(参见jb的回答)还是权限,即读/写访问等方面的问题?如果是后者,请参见File.SetAccessControl。
来自MSDN:
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
请参考如何为我的应用程序创建的文件授予所有用户完全权限?以获得更具体的示例。
根据原始问题,似乎您想禁止FileSystemRights.Delete
权限。
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
// Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(path, attributes);
Console.WriteLine("The {0} file is no longer hidden.", path);
}
else
{
// Hide the file.
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Console.WriteLine("The {0} file is now hidden.", path);
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
这里有一个在.NET Core上应该可以工作的示例:
FileSystemAccessRule rule = new (account, FileSystemRights.FullControl, AccessControlType.Allow);
new FileInfo(filePath).GetAccessControl().AddAccessRule(rule);