Change permissions of folders

2020-07-18 08:55发布

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条回答
一夜七次
2楼-- · 2020-07-18 09:38

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).

查看更多
登录 后发表回答