更改文件夹的权限

更改文件夹的权限

本文介绍了更改文件夹的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将某些文件夹权限(设置为只读")更改为ReadWriteExecute!

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);
}

如果要使用Directory.Delete(folder, true)删除此目录,则会显示以下错误消息:

If I want delete this directory with Directory.Delete(folder, true) I get this error message:

当然,该权限仍然是只读的!

Sure, the permissions are still Read-Only!

这是怎么了?

推荐答案

您可以尝试以下方法:

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

这使用按位逻辑AND运算符(& =)FileAttributes.ReadOnly的反数附加到现有的Attributes属性中(因为~是按位非).

This uses the bitwise logical AND operator (&=) to append to the existing Attributes property the inverse of FileAttributes.ReadOnly (because ~ is bitwise NOT).

这篇关于更改文件夹的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 15:16