sh H
sh H

Reputation: 57

How to remove all deny permissions on a folder without hardcoding?

I'm using microsoft's RemoveDirectorySecurity method to remove a folder's permissions.

public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
    DirectoryInfo dInfo = new DirectoryInfo(FileName);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();

    dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                        Rights,
                                                        ControlType));

    dInfo.SetAccessControl(dSecurity);
}

I hardcoded it using the Account parameter to remove all permissions.

private void RemoveAllDenyPermission(string tempDirectory, string userName)
{
    RemoveDirectorySecurity(tempDirectory, "system", FileSystemRights.FullControl, AccessControlType.Allow);
    RemoveDirectorySecurity(tempDirectory, "users", FileSystemRights.FullControl, AccessControlType.Allow);
    RemoveDirectorySecurity(tempDirectory, "Everyone", FileSystemRights.FullControl, AccessControlType.Allow);
    RemoveDirectorySecurity(tempDirectory, "Administrators", FileSystemRights.FullControl, AccessControlType.Allow);            
    RemoveDirectorySecurity(tempDirectory, userName, FileSystemRights.FullControl, AccessControlType.Allow);
}

The problem is that if you have an account other than System, User, Everyone, Administrator, that permission may remain. Is there a way to release the permissions of all accounts?

I'm using a translator so I don't know if the meaning is conveyed correctly..

Upvotes: 1

Views: 244

Answers (1)

Julian
Julian

Reputation: 934

you can loop through all ruels and then remove them.

var security = Directory.GetAccessControl(path);
var rules = security.GetAccessRules(true, true, typeof(NTAccount));

foreach (FileSystemAccessRule rule in rules)
{
    if (rule.IdentityReference.Value == accountToRemove) 
        security.RemoveAccessRuleSpecific(rule);

}

Upvotes: 2

Related Questions