C# - Windows ACL - 应用继承的权限

6 c# windows permissions acl

我一直遇到以编程方式为文件夹/注册表项分配权限的问题.我已设法使用以下代码分配继承权限:

FileSystemAccessRule rule = new FileSystemAccessRule(LOGON_USER_NAME, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);

DirectorySecurity security = new DirectorySecurity(); 
security.SetAccessRule(rule);

Directory.CreateDirectory(dir);
Directory.SetAccessControl(dir, security);
Run Code Online (Sandbox Code Playgroud)

这正确地设置了我作为管理员创建的所有子文件夹的文件权限.但是,它不会设置dir文件夹本身的权限.我已经玩了很多关于遗产和传播的排列,但没有任何快乐.

例如,我有:

dir = %programfiles%\Test
Run Code Online (Sandbox Code Playgroud)

如果我在test(%programfiles%\Test\SubFolder)中创建了一个文件夹,我为我的用户分配了完整的权限,但我没有完全权限%programfiles%\Test.这真的很烦人,因为我想给我的用户完全权限,以便对Test目录做任何事情.

我在注册表权限方面遇到了类似的问题,但我相信如果我能解决一个问题,我可以解决这两个悬而未决的问题.

有谁知道如何解决这个问题?

关心
Tris

小智 14

对于文件夹:

FileSystemAccessRule rule = new FileSystemAccessRule(LOGON_USER_NAME, 
    FileSystemRights.FullControl, AccessControlType.Allow);
Run Code Online (Sandbox Code Playgroud)

对于子文件夹和文件:

FileSystemAccessRule rule = new FileSystemAccessRule(LOGON_USER_NAME,
    FileSystemRights.FullControl, InheritanceFlags.ContainerInherit |  
    InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, 
    AccessControlType.Allow);
Run Code Online (Sandbox Code Playgroud)

这两行都需要在你的项目中.然后你得到适用于这个文件夹,子文件夹和文件的acls


Jer*_*emy 9

我不是这里的专家,但在为了我自己的目的而不得不想出这个之后,我相信Dave的答案虽然功能齐全,却过于复杂.您应该只需一条规则即可实现此目的:

FileSystemAccessRule rule = new FileSystemAccessRule(LOGON_USER_NAME,
    FileSystemRights.FullControl,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.None, 
    AccessControlType.Allow);
Run Code Online (Sandbox Code Playgroud)

PropagationFlags.InheritOnlyOP在其原始代码中使用的参数是阻止访问规则应用于对象本身的参数.

此外,您还可以在创建目录时设置目录的安全性,因为.NET为此提供了重载:

Directory.CreateDirectory(dir, security);
Run Code Online (Sandbox Code Playgroud)