Setting a file's ACL to be inherited

Jim picture Jim · Oct 10, 2012 · Viewed 12.1k times · Source

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"

Answer

Jim picture Jim · Oct 10, 2012

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...