Writing a value to a registry key with .NET

Posted: (EET/GMT+2)

 

Sometimes, you need to write to the system registry with .NET, too. Luckily, there's the convenient Microsoft.Win32.RegistryKey class to help you.

This class has a SetValue method, but if you are not careful how you open the registry key you want to write to, you might get the following error message:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll.

Additional information: Cannot write to the registry key.

Why did that happen? It happened because by default, a registry key gets opened with read-only permissions.

It is easy to overlook the second parameter of the OpenSubKey method. Unless you set the second (default) parameters to true, you will get the above error message.

The following code will demonstrate the correct way to do it:

Microsoft.Win32.RegistryKey key =
  Registry.CurrentUser.OpenSubKey("Software\\ACME",true);
int myValue = 123;
key.SetValue("My Value",myValue);
key.Close();

Not a complicated example, is it? Just call OpenSubKey the right way, and it will work out okay.