I am trying to progamrtaiclly allow write access to ASPNET account on a directory. I am using the following code to do this: (Please note that I want the "write access allowed" for ASPNET to be propagated to the child objects as well:
static void Main(string[] args)
{
FileSecurity fileSecurity;
fileSecurity = new FileSecurity();
fileSecurity.SetAccessRuleProtection(true, false);
fileSecurity.AddAccessRule(new FileSystemAccessRule("ASPNET",FileSystemRights.Write,InheritanceFlags.ObjectInherit|InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly,AccessControlType.Allow));
File.SetAccessControl("C:\\TestDir1", fileSecurity);
}
This code is resulting in the exception: "No flags can be set.\r\nParameter name: inheritanceFlags"
What could be wrong?
Got the solution, apparently I would have to do it this way:
DirectoryInfo dirInfo = new DirectoryInfo("C:\\TestDir2");
DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule("ASPNET", FileSystemRights.Write|FileSystemRights.DeleteSubdirectoriesAndFiles, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
dirInfo.SetAccessControl(dirSecurity);
As you point out, the original problem was that you were using the FileSecurity
class (which applies to files, not directories) and attempting to set the ACL for a directory, but this can happen for any of the following reasons as well:
InheritanceFlags.None
as the inheritance flag, but supply any
value other than PropagationFlags.None
for the propagation flag
(you can't propagate inheritance that doesn't exist).InheritanceFlags.None
and PropragationFlags.None
for the
respective parameters (files are not containers, and so inheritance
cannot be specified).You can see the relevant checks that the .NET Framework does in the source for the CheckFlags method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With