【发布时间】:2011-11-27 06:34:42
【问题描述】:
我想在 C# 中将文件的权限设置为“无法删除”,只能读取。但我不知道该怎么做。你能帮帮我吗?
【问题讨论】:
标签: c# file-permissions
我想在 C# 中将文件的权限设置为“无法删除”,只能读取。但我不知道该怎么做。你能帮帮我吗?
【问题讨论】:
标签: c# file-permissions
这是关于属性(参见 jb.'s answer)或权限,即读/写访问权限等吗?在后一种情况下,请参阅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);
请参阅How to grant full permission to a file created by my application for ALL users? 了解更具体的示例。
在最初的问题中,听起来您想禁止FileSystemRights.Delete 对。
【讨论】:
看看File.SetAttributes()。网上有很多关于如何使用的例子。
取自该 MSDN 页面:
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);
}
【讨论】:
你忘记在RemoveAttribute方法中复制了,就是:
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
【讨论】: