简体   繁体   English

Directory.SetAccessControl 设置不必要的权限

[英]Directory.SetAccessControl set unnecessary permissions

I am trying to set program's installation folder permissions restricted only to Administrators.我正在尝试将程序的安装文件夹权限设置为仅限于管理员。

There are two scenarios: the folder needs creation and folder already exists.有两种情况:文件夹需要创建和文件夹已经存在。

Here is my code:这是我的代码:

    public static void CreatePrivateFolder(string path)
    {
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
        DirectorySecurity securityRules = new DirectorySecurity();
        FileSystemAccessRule fsRule =
            new FileSystemAccessRule(sid, FileSystemRights.FullControl,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.None, AccessControlType.Allow);

        securityRules.SetAccessRule(fsRule);

        if (Directory.Exists(path))
        {
            Directory.SetAccessControl(path, securityRules);
        }
        else
        {
            Directory.CreateDirectory(path, securityRules);
        }                
    }

When the folder needs creation, the CreateDirectory works fine, the folder's permissions restricted only to Administrators.当文件夹需要创建时, CreateDirectory工作正常,文件夹的权限仅限于管理员。

The strange thing is when I am re-run this code and flow to SetAccessControl - the folder's permissions being reset to regular folder with no restricted access.奇怪的是,当我重新运行此代码并流向SetAccessControl - 文件夹的权限被重置为没有访问限制的常规文件夹。

What do I'm doing wrong?我做错了什么?

Folder security results (for path c:\\\\folderCheck ) :文件夹安全结果(对于路径c:\\\\folderCheck ): 在此处输入图片说明

Update anrei solution answering my question.更新anrei解决方案来回答我的问题。 However, it seem to be the same problem in a different way: If the folder already exists with unrestricted permissions, anrei's code don't seem to be work.但是,它似乎以不同的方式存在相同的问题:如果该文件夹已经存在且具有不受限制的权限,则 anrei 的代码似乎不起作用。 The folder's permissions remain unrestricted.文件夹的权限保持不受限制。

Thanks!谢谢!

Use this instead of your if (Directory.Exists(path)) block.使用它代替if (Directory.Exists(path))块。

// what is
var existingACL = Directory.GetAccessControl(path);
// remove everything from what is
foreach (FileSystemAccessRule rule in existingACL.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        existingACL.RemoveAccessRuleAll(rule);
// add yours to what is           
existingACL.AddAccessRule (fsRule);
// set again
Directory.SetAccessControl(path, existingACL);

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

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