Using SetAccessRuleProtection

The SetAccessRuleProtection method is part of ObjectSecurity, which both FileSecurity and DirectorySecurity inherit from. You use to to govern how the object access rules behave in relation to inheritance.

You get the FileSecurity or DirectorySecurity object using GetAccessControl:


            DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Windows");

            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(AccessControlSections.All);

You can then call SetAccessRuleProtection, it takes two boolean values:

isProtected
True – Protect rules from being changed by inheritance
False – Allow inheritance to change the rules
preserveInheritance
True – Preserve inheritance
False – Remove inherited rules

            const bool protectRulesFromInheritance = false;

            const bool preserveInheritance = true;

            directorySecurity.SetAccessRuleProtection(protectRulesFromInheritance, preserveInheritance);

The full example is here:


            DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Windows");

            DirectorySecurity directorySecurity = 
                directoryInfo.GetAccessControl(AccessControlSections.All);

            // true to protect rules from being changed by inheritance
            // or
            // false to allow inheritance to change the rules
            const bool protectRulesFromInheritance = false;

            // true to preserve inheritance
            // or 
            // false to remove inherited rules
            const bool preserveInheritance = true;

            directorySecurity.SetAccessRuleProtection(
                                protectRulesFromInheritance, 
                                preserveInheritance);

            DirectoryInfo newDir = Directory.CreateDirectory(@"C:\New");

            newDir.SetAccessControl(directorySecurity);



Comments

  1. sadegh July 18th

    Comment Arrow

    thanQ


Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.