在C#中设置文件权限

我想在C#中将文件的权限设置为“无法删除”,只能读取。 但我不知道该怎么做。 你能帮助我吗 ?

看一下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; } 

这是关于属性(参见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