且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

授予NTFS权限时,继承的权限丢失

更新时间:2022-11-25 09:56:03

在处理Dropkick的安全模块时,使用文件系统权限时遇到了类似的问题.我们提出的解决方案如下.这样将成功设置任何文件夹的权限,而无需更改该文件夹的继承规则.

We ran into similar issues working with file system permission while working on Dropkick's security module. The solution we came up with is as follows. This will successfully set permissions on any folder without changing the inheritance rules on the folder.

    public void SetFileSystemRights(string target, string group, FileSystemRights permission)
    {
        if (!IsDirectory(target) && !IsFile(target))
            return;

        var oldSecurity = Directory.GetAccessControl(target);
        var newSecurity = new DirectorySecurity();

        newSecurity.SetSecurityDescriptorBinaryForm(oldSecurity.GetSecurityDescriptorBinaryForm());

        var accessRule = new FileSystemAccessRule(group,
                                                  permission,
                                                  InheritanceFlags.None,
                                                  PropagationFlags.NoPropagateInherit,
                                                  AccessControlType.Allow);
        bool result;
        newSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out result);

        if (!result) Log.AddError("Something wrong happened");

        accessRule = new FileSystemAccessRule(group,
                                              permission,
                                              InheritanceFlags.ContainerInherit |
                                              InheritanceFlags.ObjectInherit,
                                              PropagationFlags.InheritOnly,
                                              AccessControlType.Allow);

        result = false;
        newSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result);
        if (!result) Log.AddError("Something wrong happened");

        Directory.SetAccessControl(target, newSecurity);

        if (result) Log.AddGood("Permissions set for '{0}' on folder '{1}'", group, target);

        if (!result) Log.AddError("Something wrong happened");
    }

找到了我最初用来解决此问题的链接.