10

Here is how we manually assign the permissions to a registry key:

To assign permissions to a registry key

  • Open Registry Editor. Click the key to which you want to assign permissions.

  • On the Edit menu, click Permissions.

  • Assign an access level to the selected key as follows:

  • To grant the user permission to read the key contents, but not save any changes made to the file, under Permissions for name, for Read, select the Allow check box.

  • To grant the user permission to open, edit, and take ownership of the selected key, under Permissions for name, for Full Control, select the Allow check box.

  • To grant the user special permission in the selected key, click Advanced.

So my question is, would it be possible to do it programmatically? Say, if I want to grant Users full control permission on a particular subkey, how should I write the code in C#? Thanks very much.

woodykiddy
  • 6,074
  • 16
  • 59
  • 100

3 Answers3

7
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine;
RegistrySecurity rs = new RegistrySecurity();
rs = key.GetAccessControl();
string currentUserStr = Environment.UserDomainName + "\\" + Environment.UserName;
rs.AddAccessRule(
    new RegistryAccessRule(
        currentUserStr, 
        RegistryRights.WriteKey 
        | RegistryRights.ReadKey 
        | RegistryRights.Delete 
        | RegistryRights.FullControl, 
        AccessControlType.Allow));

This will assign the access rights to the specified user to the registry key 'key'

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
Ajay Bhasy
  • 1,920
  • 1
  • 26
  • 38
5

RegistrySecurity class is also useful here. So we can write the following code to apply access rules on the registry key for a current user.

RegistrySecurity rs = new RegistrySecurity(); // it is right string for this code
string currentUserStr = Environment.UserDomainName + "\\" + Environment.UserName;
rs.AddAccessRule(new RegistryAccessRule(currentUserStr, RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.FullControl, AccessControlType.Allow));
Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
woodykiddy
  • 6,074
  • 16
  • 59
  • 100
  • For giving permissions to the "everyone" user in a language agnostic way, pass `new SecurityIdentifier(WellKnownSidType.WorldSid, null)` instead of `currentUserStr`. – Uwe Keim Dec 08 '15 at 10:44
1

It is about RegSetKeySecurity API, which is interfaced to from .NET code via RegistryKey.SetAccessControl, see Using RegSetKeySecurity to avoid registry redirection

Community
  • 1
  • 1
Roman R.
  • 68,205
  • 6
  • 94
  • 158