简体   繁体   中英

Copy parent folder permissions to child files

So, basically I have an issue where these files are being moved into folders from a couple layers up and the permissions of the child are not being inheritied for some reason. From what I can tell this is the intended function of windows but I need it to work different so I decided to do this:

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

However this is generating an error while doing "fs.addaccessrule" saying:

system.argumentexception no flags can be set

I can't figure out how i'm supposed to move the permissions from the parent folder to the child file.

This is the solution I came up with, just creating a new rule based on the rule I want to use and removing the inheritedflags.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM