Writing to registry in a C# application

First of all if you want to edit key under LocalMachine you must run your application under admin rights (better use CurrentUser it's safer or create the key in installer). You have to open key in edit mode too (OpenSubKey method) to add new subkeys. I've checked the code and it works. Here is the code.

RegistryKey key = Registry.LocalMachine.OpenSubKey("Software",true);

key.CreateSubKey("AppName");
key = key.OpenSubKey("AppName", true);


key.CreateSubKey("AppVersion");
key = key.OpenSubKey("AppVersion", true);

key.SetValue("yourkey", "yourvalue");

You can use the following code to create and open the required registry keys.

RegistryKey SoftwareKey   = Registry.LocalMachine.OpenSubKey("Software",true);

RegistryKey AppNameKey    = SoftwareKey.CreateSubKey("AppName");
RegistryKey AppVersionKey = AppNameKey.CreateSubKey("AppVersion");

AppVersionKey.SetValue("yourkey", "yourvalue");

You can basically use CreateSubKey for all your application settings, as it will open the key for write access, if it already exists, and create it otherwise. There is no need to create first, and then open. OpenSubKey comes in handy when you are absolutely certain the key already exists, like in this case, with "HKEY_LOCAL_MACHINE\SOFTWARE\"


Also check if your registry calls are getting virtualised. See here for more information.

It can happen if your application is not UAC aware and occurs for compatibility reasons.

Real path
HKEY_LOCAL_MACHINE\Software\FooKey

Virtual path
HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software\FooKey

Try to open HKLM\Software first. Then create key for your program, and then create key for version. Howewer, your key could be placed at HKLM\software\WOW6432Node. Check this.


The problem is you don't have enough privileges. Here is a way that works for my:

RegistryKey myKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
myKey = myKey.OpenSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);

if (myKey != null)
{
    myKey.SetValue("DefaultPrinterId", ldiPrinters[e.RowIndex].id, RegistryValueKind.String);
    myKey.Close();
}

With RegistryKey.OpenBaseKey you open the correct registry, because when you don't have permissions the registry that you write, it does in another location.