0

I'm creating a registry key like this:

Key = Registry.CurrentUser.CreateSubKey("Mykey");

Then open it when my application runs the second time:

Key = Registry.CurrentUser.OpenSubKey("Mykey");

But I got an access denied when trying to create its subkey:

Subkey = Key.CreateSubKey("Mysubkey"); <-- Runtime error here

Any suggestion why? I guess it's because I didn't set the permissions on 'Mykey' at the time it is created. But I just don't know how to set these permissions.

jondinham
  • 8,271
  • 17
  • 80
  • 137

2 Answers2

1

You can set your app to run on full trust in your project properties, also, you can have your assemblies signed with a key from the "Signing" tab on the project properties page. Finally, run your app as an administrator and set it to run on admin mode by right clicking on the app launch icon and going into Compatibility tab and checking the "Run this program as an Administrator" checkbox. Registry handling requires full trust on the app to run properly. Hope this helps.

EDIT: Or alternatively, as people have mentioned, use local settings.

Aman
  • 548
  • 1
  • 4
  • 11
0

The answer is that the 'write' permission must be added to 'OpenSubKey' as a boolean value 'true', like this:

Key = Registry.CurrentUser.OpenSubKey("Mykey",true);

And it gives more permissions when doing a CreateSubKey by adding a parameter:

Key = Registry.CurrentUser.CreateSubKey("Mykey",
RegistryKeyPermissionCheck.ReadWriteSubTree);

However, this doesn't guarantee the key is accessible by any user, any application. And more, CreateSubKey also does the job for OpenSubKey when the key is already existing.

jondinham
  • 8,271
  • 17
  • 80
  • 137
  • it is still bad programming practice to persist any form of user settings to the Registry. – Lloyd Oct 30 '11 at 13:29
  • @lloyd What are you talking about? Why not use HKCU area of registry for user settings? – David Heffernan Oct 30 '11 at 13:39
  • Why persist something to Registry when you have a user and Application specific system available that is specifically designed for this purpose and avoids all security and domain issues. Most corporate users do not have any ability to access the registry. – Lloyd Oct 30 '11 at 13:52