Eli
Eli

Reputation: 4956

Directory.SetAccessControl set unnecessary permissions

I am trying to set program's installation folder permissions restricted only to Administrators.

There are two scenarios: the folder needs creation and folder already exists.

Here is my code:

    public static void CreatePrivateFolder(string path)
    {
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
        DirectorySecurity securityRules = new DirectorySecurity();
        FileSystemAccessRule fsRule =
            new FileSystemAccessRule(sid, FileSystemRights.FullControl,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.None, AccessControlType.Allow);

        securityRules.SetAccessRule(fsRule);

        if (Directory.Exists(path))
        {
            Directory.SetAccessControl(path, securityRules);
        }
        else
        {
            Directory.CreateDirectory(path, securityRules);
        }                
    }

When the folder needs creation, the CreateDirectory works fine, the folder's permissions restricted only to Administrators.

The strange thing is when I am re-run this code and flow to SetAccessControl - the folder's permissions being reset to regular folder with no restricted access.

What do I'm doing wrong?

Folder security results (for path c:\\folderCheck) : enter image description here

Update anrei solution answering my question. However, it seem to be the same problem in a different way: If the folder already exists with unrestricted permissions, anrei's code don't seem to be work. The folder's permissions remain unrestricted.

Thanks!

Upvotes: 2

Views: 1954

Answers (1)

andrei.ciprian
andrei.ciprian

Reputation: 3025

Use this instead of your if (Directory.Exists(path)) block.

// what is
var existingACL = Directory.GetAccessControl(path);
// remove everything from what is
foreach (FileSystemAccessRule rule in existingACL.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        existingACL.RemoveAccessRuleAll(rule);
// add yours to what is           
existingACL.AddAccessRule (fsRule);
// set again
Directory.SetAccessControl(path, existingACL);

Upvotes: 1

Related Questions