将 parent 个文件夹权限复制到 child 个文件

Copy parent folder permissions to child files

所以,基本上我遇到了一个问题,即这些文件从几层向上移动到文件夹中,并且 child 的权限由于某种原因没有被继承。据我所知,这是 windows 的预期功能,但我需要它以不同的方式工作,所以我决定这样做:

foreach (string directory in System.IO.Directory.GetDirectories(@"path", "*", SearchOption.TopDirectoryOnly))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
    DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory);
    FileSecurity FS = new FileSecurity();
    System.IO.FileInfo FI = new FileInfo(file);
    foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, true, typeof(NTAccount)))
    {
        FS.AddAccessRule(rule);
    }
    FI.SetAccessControl(FS);
}
}

然而,这在执行 "fs.addaccessrule" 时会产生错误:

system.argumentexception no flags can be set

我不知道应该如何将权限从 parent 文件夹移动到 child 文件。

这是我想出的解决方案,只需根据我要使用的规则创建一个新规则并删除继承的标志。

foreach (string directory in System.IO.Directory.GetDirectories(@"path", "*", SearchOption.AllDirectories))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
    DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory, AccessControlSections.Access);
    FileSecurity FS = new FileSecurity();
    System.IO.FileInfo FI = new FileInfo(file);
    foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, false, typeof(NTAccount)))
    {
        FileSystemAccessRule nRule = new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, InheritanceFlags.None, rule.PropagationFlags, rule.AccessControlType);
        FS.AddAccessRule(nRule);
    }
    FI.SetAccessControl(FS);
}
}