woodykiddy
woodykiddy

Reputation: 6455

Programmatically assign the permission to a registry subkey

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

To assign permissions to a registry key

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.

Upvotes: 10

Views: 15630

Answers (3)

Ajay Bhasy
Ajay Bhasy

Reputation: 2000

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'

Upvotes: 7

woodykiddy
woodykiddy

Reputation: 6455

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

Upvotes: 5

Roman Ryltsov
Roman Ryltsov

Reputation: 69672

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

Upvotes: 1

Related Questions