Bob
Bob

Reputation: 16551

How do I add ACL rules without replacing existing ones?

I would like to add some new ACL rules alongside existing ones. I am currently using SetAccessRule, with the expectation that adding new rules also keeps the old ones. According to the 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.

However, in practice, I've found that adding a new rule actually overwrites any previous rules (belonging to the same user/SID?). This seems to contradict what the documentation says.

My current intention is to assign both read and write permissions, but in separate calls. Unfortunately, the latter permissions overwrite the first. In the example code below, the result is only the read permissions are assigned. If I comment out that block, then only the write permissions are assigned. This could be fixed with an additional if condition to assign both permissions, but it still overwrites any existing permissions on the directory, which is undesired.

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);

How should I handle adding new rules while keeping existing ones? And, is the documentation incorrect, am I misinterpreting it, or is my code incorrect?

Upvotes: 2

Views: 3856

Answers (1)

Jason
Jason

Reputation: 3960

Try using DirectorySecurity.AddAccessRule method instead to append/add permissions instead or replacing, see this MSDN link for more info

security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

Upvotes: 2

Related Questions