Search code examples
c#.netacl

How to reset and delete ACL permissions for account?


OS Windows 7 SP1 x64

I set ACL permissions to my folder for some account:

var accessRule = new FileSystemAccessRule(account,
    fileSystemRights: FileSystemRights.Modify,
    inheritanceFlags: InheritanceFlags.ContainerInherit |
    InheritanceFlags.ObjectInherit,
    propagationFlags: PropagationFlags.None,
    type: AccessControlType.Allow);

// Get a DirectorySecurity object that represents the 
// current security settings.
DirectorySecurity dSecurity = directoryinfo.GetAccessControl();

// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(accessRule);

// Set the new access settings.
directoryinfo.SetAccessControl(dSecurity);

At this case I allowed read and write for account. It works fine.

But later I wanted to change the rights for that account: to allow read only permissions. I use such code:

var accessRule = new FileSystemAccessRule(account,
    fileSystemRights: FileSystemRights.ReadAndExecute,
    inheritanceFlags: InheritanceFlags.ContainerInherit |
    InheritanceFlags.ObjectInherit,
    propagationFlags: PropagationFlags.None,
    type: AccessControlType.Allow);

// Get a DirectorySecurity object that represents the 
// current security settings.
DirectorySecurity dSecurity = directoryinfo.GetAccessControl();

// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(accessRule);

// Set the new access settings.
directoryinfo.SetAccessControl(dSecurity);

But the account has write permissions still. How can I fix it? Also, how can I remove the ACL permissions for that account when I will want to do it later?


Solution

  • It is quite easy:

    dSecurity = directoryinfo.GetAccessControl();
    
    accessRule = new FileSystemAccessRule(account,
        fileSystemRights: FileSystemRights.ReadAndExecute,
        inheritanceFlags: InheritanceFlags.ContainerInherit |
        InheritanceFlags.ObjectInherit,
        propagationFlags: PropagationFlags.None,
        type: AccessControlType.Allow);
    
    dSecurity.SetAccessRule(accessRule);
    directoryinfo.SetAccessControl(dSecurity);
    

    and for removing:

    dSecurity = directoryinfo.GetAccessControl();
    
    accessRule = new FileSystemAccessRule(account, 0, 0);
    dSecurity.RemoveAccessRuleAll(accessRule);
    directoryinfo.SetAccessControl(dSecurity);
    

    Note that the SetAccessRule will work even if there is no access rule for the account (so it can even be used to do the initial Add)