问题
I want to change some folder permissions (set to Read-Only) to ReadWriteExecute!
I wrote this code, but the folder permission is still Read-Only:
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);
}
If I want delete this directory with Directory.Delete(folder, true)
I get this error message:
"Access to the path 'entries' is denied."
Sure, the permissions are still Read-Only!
What is wrong here?
回答1:
You could try something like this:
var dirInfo = new DirectoryInfo(folder);
dirInfo.Attributes &= ~FileAttributes.ReadOnly;
This uses the bitwise logical AND operator (&=) to append to the existing Attributes property the inverse of FileAttributes.ReadOnly
(because ~
is bitwise NOT).
来源:https://stackoverflow.com/questions/10175270/change-permissions-of-folders