views:

13

answers:

1

I'm having a problem where we create a file in temp and then move to our application directory, and we've found that a moved file does not inherit permissions from its new parent folder.

I know I could use File.Copy (as creating a new file will inherit the permissions), but for performance reasons we don't want to do this.

The site referenced above suggests using SetNamedSecurityInfo, which I can access using the PInvoke approach. However I thought there might be some way to achieve this using the core .NET API, such as new FileInfo("C:\Test.txt").GetAccessControl() as the article above is four years old now.

Is there a better way to 'refresh' a files permissions to match that of its parent folder?

A: 

After some testing, this is the code I'm going with:

FileInfo fi = new FileInfo(myTargetFile);
var acl = fi.GetAccessControl();
var rules = acl.GetAccessRules(true, true, typeof(SecurityIdentifier));

//Remove all existing permissions on the file
foreach (var rule in rules.Cast<FileSystemAccessRule>())
{
  acl.RemoveAccessRule(rule);
}

//Allow inherited permissions on the file
acl.SetAccessRuleProtection(false, false);
fi.SetAccessControl(acl);
MattH