I am trying to have my C# program secure a local existing directory on a windows machine. For security reasons, I only want accounts in the administrators group to have access to this folder. The existing folder is one that my program previously created and will be owned by the current running user, so I will need to both add privileges for the admin group and then remove privileges for the current user.
I am able to add the admin group’s privileges to the folder, but I can’t figure out how to remove the current user’s permissions. I am giving the admin group permissions as follows:
DirectorySecurity directorySecurity = new DirectorySecurity();
IdentityReference adminId = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
FileSystemAccessRule adminAccess = new FileSystemAccessRule(
adminId,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow);
directorySecurity.AddAccessRule(adminAccess);
// set the owner and the group to admins
directorySecurity.SetOwner(adminId);
directorySecurity.SetGroup(adminId);
Directory.SetAccessControl("path-to-my-directory", directorySecurity);
I now see the real issue. You were already effectively removing the other user’s access by setting the directory security to a brand new object instead of getting the existing directory security and modifying it, but your directory was still getting the inherited permissions from the parent.
What you need on your new directory security object to remove the parent inheritance. You can do this through the SetAccessRuleProtection method. You can use your above code as is, but add this line before you set the access control on the directory.