17.11. Granting/Revoking Access to a File or Registry Key

Problem

You need to change the security privileges of either a file or registry key programmatically.

Solution

The code shown in Example 17-13 grants and then revokes the ability to perform write actions on a registry key.

Example 17-13. Granting and revoking the right to perform write actions on a registry key

public static void GrantRevokeRegKeyRights()
{
    NTAccount user = new NTAccount(@"WRKSTN\ST");

    using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(
                            @"SOFTWARE\MyCompany\MyApp"))
    {
        GrantRegKeyRights(regKey, user, RegistryRights.WriteKey,
           InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow);
        RevokeRegKeyRights(regKey, user, RegistryRights.WriteKey,
                       InheritanceFlags.None, PropagationFlags.None,
                       AccessControlType.Allow)
    }
}

public static void GrantRegKeyRights(RegistryKey regKey,
                                     NTAccount user,
                                     RegistryRights rightsFlags,
                                     InheritanceFlags inherFlags,
                                     PropagationFlags propFlags,
                                     AccessControlType actFlags)
{
    Registry Security regSecurity = regKey.GetAccessControl(); RegistryAccessRule rule = new RegistryAccessRule(user, rightsFlags, inherFlags, propFlags, actFlags); regSecurity.AddAccessRule(rule); regKey.SetAccessControl(regSecurity); } public static void RevokeRegKeyRights(RegistryKey regKey, NTAccount user, RegistryRights rightsFlags, InheritanceFlags inherFlags, PropagationFlags propFlags, AccessControlType actFlags) { RegistrySecurity regSecurity = regKey.GetAccessControl(); RegistryAccessRule ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.