If you are trying to modify the registry via a Visual Studio program there are two big things you need to do to ensure that it is done right.

First, you must be running as a user account with privileges. In Windows Vista or later, you will likely have to elevate the program to run as administrator. This can be done a couple ways, the simple but tedious approach would be to right click the built EXE and perform the usual ‘Run as Administrator’.

Automating this is quite simple, within the app.manifest under your Solution Properties folder (in Solution Explorer). You will need this piece of code:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

This will cause UAC to fire automatically to raise persmissions.

Second, one that tortured me when I was trying to figure out why my Administrator elevated program still provided errors (then again after I realized how simple it was). If you are still receiving the error be sure to make sure that the Registry is opened with WRITE access and not read only.

These would generally show up on a SetValue command of a Microsoft.Win32.RegistryKey object with error “UnauthorizedAccessException was unhandled: Cannot write to the registry key.”.

The solution for that one?

key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services", true);

Make sure you have the the second parameter of OpenSubKey set to true which allows for write access! And make sure if your working with multiple keys that you did not miss one like I did!

No Comments

There are no comments related to this article.