将父文件夹权限复制到子文件

时间:2017-10-11 14:54:15

标签: c# .net windows shared-directory

所以,基本上我有一个问题,这些文件被从几层中移入文件夹中,并且由于某种原因未继承子项的权限。从我可以看出这是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

我无法弄清楚我应该如何将权限从父文件夹移动到子文件。

1 个答案:

答案 0 :(得分:0)

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

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