2012-04-16 157 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