2012-04-16 160 views
4

我想將某些文件夾權限(設置爲只讀)更改爲ReadWriteExecute!更改文件夾的權限

我寫了這個代碼,但該文件夾的權限仍是隻讀:

private void ChangePermissions(string folder) 
{ 
    string userName = Environment.UserName; 

    FileSystemAccessRule accessRule = new FileSystemAccessRule(userName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit 
       | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); 

    DirectoryInfo directoryInfo = new DirectoryInfo(folder); 
    DirectorySecurity directorySec = directoryInfo.GetAccessControl(); 


    directorySec.AddAccessRule(accessRule); 
    directoryInfo.SetAccessControl(directorySec); 
} 

如果我想這個目錄刪除與Directory.Delete(folder, true)我收到此錯誤信息:

「訪問路徑'條目'被拒絕。「

當然,權限仍爲只讀!這裏有什麼問題?

謝謝!

回答

3

你可以嘗試這樣的事:

var dirInfo = new DirectoryInfo(folder); 
dirInfo.Attributes &= ~FileAttributes.ReadOnly; 

這將使用compound assignment運算符和位運算符&追加到現有的屬性屬性倒數(因爲~不按位)的FileAttributes.ReadOnly

+0

同樣的錯誤。 'entries'路徑是文件夾中的文件,也許我必須遞歸更改權限? (但我不明白爲什麼只讀標誌仍然設置爲根文件夾?) – leon22 2012-04-16 13:59:53

+1

如果您需要遞歸更改文件權限,這個SO帖子可能會有所幫助:http://stackoverflow.com/questions/191399/how-對於每個文件夾使用-c- – Robbie 2012-04-16 14:03:46

+0

Thx來更改只讀文件屬性。使用來自http://stackoverflow.com/questions/191399/how-do-i-change-the-read-only-file-attribute-for-each-file-in-a-folder-using-c的代碼很好! – leon22 2012-04-16 14:12:48