5

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?

edosoft
  • 17,121
  • 25
  • 77
  • 111
coder_bro
  • 10,503
  • 13
  • 56
  • 88

2 Answers2

9

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); 
coder_bro
  • 10,503
  • 13
  • 56
  • 88
  • It appears that setting inheritance flags doesn't work unless an existing FileSecurity object is used? This doesn't make testing any easier. – wesm Oct 07 '14 at 21:21
2

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.

Dusty
  • 3,946
  • 2
  • 27
  • 41