13

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"

Community
  • 1
  • 1
Jim
  • 1,892
  • 1
  • 19
  • 39

2 Answers2

19

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

Community
  • 1
  • 1
Jim
  • 1,892
  • 1
  • 19
  • 39
  • I was searching for this for ages .. fs.SetAccessRuleProtection(false, false); does the trick :D – spetzz Nov 13 '14 at 16:44
17

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);
TGasdf
  • 970
  • 10
  • 14