2011-09-28 29 views
5

Tôi muốn đặt quyền trên tệp thành "không thể xóa" trong C#, chỉ có thể đọc được. Nhưng tôi không biết làm thế nào để làm điều này. Bạn có thể giúp tôi được không ?Đặt quyền tệp trong C#

Trả lời

7

Hãy xem File.SetAttributes(). Có rất nhiều ví dụ trực tuyến về cách sử dụng nó.

Taken từ đó MSDN page:

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); 
     } 
2

Bạn quên sao chép trong phương pháp RemoveAttribute, đó là:

private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) 
    { 
     return attributes & ~attributesToRemove; 
    } 
0

Đây có phải là về các thuộc tính (. Thấy jb của câu trả lời) hoặc quyền , nghĩa là truy cập đọc/ghi, v.v ...? Trong trường hợp sau, hãy xem File.SetAccessControl.

Từ 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); 

Xem How to grant full permission to a file created by my application for ALL users? cho một ví dụ cụ thể hơn.

Trong câu hỏi ban đầu, có vẻ như bạn không muốn cho phép FileSystemRights.Delete bên phải.

Các vấn đề liên quan