Setting a file's ACL to be inherited
Asked Answered
D

2

15

I am looking for a way in c# to reset a file's permissions to be inherited from the parent as if the file was created or copied to that directory.

I can't seem to find anything on this from a file standpoint (I found a reference or two for directories, but I can't get them to translate to a file for some reason). C# - Windows ACL - Applying Inherited Permissions, for example. But I am not sure what the value for LOGON_USER_NAME is supposed to be and as far as I can get is getting a System.ArgumentExcpetion of "no flags can be set"

Dandelion answered 10/10, 2012 at 4:17 Comment(0)
D
21

I finally found the answer over here. File.Move does not inherit permissions from target directory?

var fs = File.GetAccessControl(destination);
fs.SetAccessRuleProtection(false, false);
File.SetAccessControl(destination, fs);

Update

While the code snip above does add in the inherited permissions, it does not remove any existing explicit permissions. My final code looks more like this.

string destination = @"<my file>";
FileInfo fileInfo;
FileSecurity fileSecurity;
FileSystemAccessRule fileRule;
AuthorizationRuleCollection fileRules;

fileInfo = new FileInfo(destination);
fileSecurity = fileInfo.GetAccessControl();
fileSecurity.SetAccessRuleProtection(false, false);
/*
 * Only fetch the explicit rules since I want to keep the inherited ones. Not 
 * sure if the target type matters in this case since I am not examining the
 * IdentityReference.
 */
fileRules = fileSecurity.GetAccessRules(includeExplicit: true, 
                         includeInherited: false, targetType: typeof(NTAccount));
/*
 * fileRules is a AuthorizationRuleCollection object, which can contain objects 
 * other than FileSystemAccessRule (in theory), but GetAccessRules should only 
 * ever return a collection of FileSystemAccessRules, so we will just declare 
 * rule explicitly as a FileSystemAccessRule.
 */
foreach (FileSystemAccessRule rule in fileRules)
{
    /*
     * Remove any explicit permissions so we are just left with inherited ones.
     */
    fileSecurity.RemoveAccessRule(rule);
}
fileInfo.SetAccessControl(fileSecurity);

Update 2

Or, simply use TGasdf's more concise 3 line solution that is elsewhere on this page...

Dandelion answered 10/10, 2012 at 14:27 Comment(1)
I was searching for this for ages .. fs.SetAccessRuleProtection(false, false); does the trick :DDamaris
S
20

The accepted answer where the explicit permissions are removed felt a bit too complicated for my taste so I tried to create a new FileSecurity. The following seems to work, and the resulting permissions are to use only the inherited permissions:

var fs = new System.Security.AccessControl.FileSecurity();
fs.SetAccessRuleProtection(false, false);
File.SetAccessControl(destination, fs);
Sexivalent answered 10/10, 2016 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.