如何查看是否为文件或文件夹取消选中“包含可继承权限”?

时间:2012-04-10 02:18:37

标签: c# .net windows permissions filesystems

我正在C#中编写一个小实用程序,以确保指定的文件夹及其所有内容具有适当的访问权限(我希望赋予Authenticated Users组完全访问权限)。以下代码似乎可以正常用于更新顶级文件夹的ACL(访问控制列表):

SecurityIdentifier allUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
FileSystemAccessRule newRule = new FileSystemAccessRule(allUsers,
    FileSystemRights.FullControl, iFlags,
    PropagationFlags.None, AccessControlType.Allow);

DirectoryInfo info = new DirectoryInfo(folderPath);
DirectorySecurity security = info.GetAccessControl();
security.AddAccessRule(newRule);
info.SetAccessControl(security);
但是,我注意到,这个新的访问规则不会传播到在其安全属性中未选中“包含可继承权限...”选项的子文件夹。这才有意义。所以,我想要做的是为任何这样的子文件夹重新打开安全权限继承。

我的挖掘发现ObjectSecurity.SetAccessRuleProtection方法应该是我需要的一半。但是,对于已经继承父级DACL的对象盲目使用上述方法似乎很草率。因此,我想确定哪些对象的权限继承已关闭,但我似乎无法找到返回此信息的相应方法或属性。有吗?我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:4)

我记得使用过这样的东西:

DirectoryInfo d = new DirectoryInfo(@"e:\test1");
DirectorySecurity acl = d.GetAccessControl();
if (acl.GetAccessRules(false, true, typeof(System.Security.Principal.SecurityIdentifier)).Count >0)
    // -- has inherited permissions
else
    // -- has no inherited permissions

我也试图找到一种方法来检查这个,但我找不到任何方法(即使在C ++中)。所以我最终使用了上面的代码。它就像一个魅力。

答案 1 :(得分:1)

似乎有一种管理方式可以做到这一点:

DirectorySecurity ds = System.IO.Directory.GetAccessControl(@"C:\test");
byte[] rawBytes = ds.GetSecurityDescriptorBinaryForm();
RawSecurityDescriptor rsd = new RawSecurityDescriptor(rawBytes, 0);

if ((rsd.ControlFlags & ControlFlags.DiscretionaryAclProtected) == 
                        ControlFlags.DiscretionaryAclProtected)
{
    // "Include inheritable permissions from this object's parent" is unchecked
}
else
{
    // "Include inheritable permissons from this object's parent" is checked
}

答案 2 :(得分:1)

C#的DirectorySecurity类现在似乎包含AreAccessRulesProtected属性,当继承为true时返回disabled,而当继承为{{1}时返回false }。

因此,您可以简单地使用:

enabled

在此感谢@Wizou的提示!