user884248
user884248

Reputation: 2244

CreateSubKey always causes exception: "Cannot write to the registry key"

The code is really quite simple:

var key = Registry.LocalMachine.OpenSubKey("Software").CreateSubKey("somekey", RegistryKeyPermissionCheck.ReadWriteSubTree);

...but I keep getting the exception "Cannot write to the registry key", even when I run VS2010 (or the compiled code) as Administrator. What am I doing wrong? Running .Net Framework 4 Client Profile.

Upvotes: 1

Views: 405

Answers (1)

David Heffernan
David Heffernan

Reputation: 613382

You are trying to write to HKEY_LOCAL_MACHINE. Access to HKEY_LOCAL_MACHINE is restricted by UAC. Your user may well be an administrator, but unless the process is started with elevated rights, UAC will prevent write access.

In order to write to HKEY_LOCAL_MACHINE you will need to ensure that the Registry access is performed in code that is running with elevated rights. To do that, you will need to either:

  1. Add a UAC manifest to your application to force it to execute with elevated rights. However, this means that the user will have to deal with the UAC elevation prompt every time the application is run.

  2. If you do not want to elevate your application, you will need to separate the parts of code that need elevation into a separate process, or into a COM object instantiated via the COM Elevation Moniker, whenever your application needs to perform an elevated operation.

Upvotes: 1

Related Questions