Setting access rights for a directory - receiving

2019-06-21 07:58发布

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?

标签: c# security
2条回答
劫难
2楼-- · 2019-06-21 08:12

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.

查看更多
相关推荐>>
3楼-- · 2019-06-21 08:18

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); 
查看更多
登录 后发表回答