我想在现有规则的旁边添加一些新的 ACL 规则。我目前正在使用 SetAccessRule
,希望添加新规则也能保留旧规则。根据documentation for SetAccessRule
,
The SetAccessRule method adds the specified access control list (ACL) rule or overwrites any identical ACL rules that match the FileSystemRights value of the rule parameter. For example, if the rule parameter specifies a Read value and the SetAccessRule method finds an identical ACL rule that specifies the Read value, the identical rule will be overwritten. If the SetAccessRule method finds an identical ACL rule that specifies the Write value, the identical rule will not be overwritten.
但是,在实践中,我发现添加新规则实际上会覆盖任何以前的规则(属于同一用户/SID?)。这似乎与文档所说的相矛盾。
我当前的意图是分配读取和写入权限,但在单独的调用中。不幸的是,后一个权限会覆盖第一个权限。在下面的示例代码中,结果是仅分配了读取权限。如果我注释掉该 block ,则仅分配写入权限。可以使用附加的 if
条件来分配这两种权限来修复此问题,但它仍然会覆盖目录上的任何现有权限,这是不希望的。
DirectoryInfo directory = new DirectoryInfo(abspath);
DirectorySecurity security = directory.GetAccessControl();
security.SetAccessRuleProtection(false, true);
if (perm.Contains("write"))
{
security.SetAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
if (perm.Contains("read"))
{
security.SetAccessRule(new FileSystemAccessRule(user, FileSystemRights.ReadAndExecute | FileSystemRights.Traverse, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
directory.SetAccessControl(security);
我应该如何在保留现有规则的同时添加新规则?而且,文档是否不正确,我是否误解了它,或者我的代码是否不正确?
最佳答案
尝试使用 DirectorySecurity.AddAccessRule
方法来追加/添加权限或替换,请参阅此 MSDN link了解更多信息
security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
关于c# - 如何添加 ACL 规则而不替换现有规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035999/