【问题标题】:Directory.SetAccessControl set unnecessary permissionsDirectory.SetAccessControl 设置不必要的权限
【发布时间】:2016-02-12 10:32:56
【问题描述】:

我正在尝试将程序的安装文件夹权限设置为仅限管理员。

有两种情况:需要创建的文件夹和已经存在的文件夹。

这是我的代码:

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

当需要创建文件夹时,CreateDirectory 工作正常,文件夹的权限仅限于管理员。

奇怪的是,当我重新运行此代码并流向 SetAccessControl 时 - 文件夹的权限被重置为没有限制访问的常规文件夹。

我做错了什么?

文件夹安全结果(路径c:\\folderCheck):

更新 anrei solution 回答我的问题。 但是,它似乎以不同的方式出现了相同的问题: 如果该文件夹已经存在且具有不受限制的权限,则 anrei 的代码似乎不起作用。 文件夹的权限不受限制。

谢谢!

【问题讨论】:

    标签: c# directory file-permissions acl


    【解决方案1】:

    用这个代替你的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);
    

    【讨论】:

    • @anrei,谢谢你的回答。当文件夹已经存在且具有限制权限时,您的解决方案有效。但是,当文件夹在没有限制权限的情况下存在时,代码不会覆盖这些规则并且文件夹仍然可以访问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多