Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting access rights for a directory - receiving exception "No flags can be set"

Tags:

c#

security

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?

like image 987
coder_bro Avatar asked Jan 19 '09 11:01

coder_bro


2 Answers

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); 
like image 170
coder_bro Avatar answered Oct 20 '22 04:10

coder_bro


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:

  1. When setting a rule for a directory, you specify 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).
  2. When setting a rule for a file, specify any value other than 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.

like image 25
Dusty Avatar answered Oct 20 '22 04:10

Dusty