简体   繁体   中英

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 ) : 在此处输入图片说明

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM