简体   繁体   English

更改文件夹的权限

[英]Change permissions of folders

I want to change some folder permissions (set to Read-Only) to ReadWriteExecute! 我想将一些文件夹权限(设置为只读)更改为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: 如果我想用Directory.Delete(folder, true)删除此目录,我收到此错误消息:

"Access to the path 'entries' is denied." “拒绝访问路径'条目'。”

Sure, the permissions are still Read-Only! 当然,权限仍然是只读的!

What is wrong here? 这有什么不对?

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). 这使用按位逻辑AND运算符(&=)将现有的Attributes属性附加到FileAttributes.ReadOnly的反转(因为~是按位NOT)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM