C# – Writing to registry in a C# application

cregistry

I'm trying to write to the registry using my C# app.

I'm using the answer given here: Writing values to the registry with C#

However for some reason the key isn't added to the registry.

I'm using the following code:

string Timestamp = DateTime.Now.ToString("dd-MM-yyyy");

string key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\"+Application.ProductName+"\\"+Application.ProductVersion;
string valueName = "Trial Period";

Microsoft.Win32.Registry.SetValue(key, valueName, Timestamp, Microsoft.Win32.RegistryValueKind.String);

The Application.name and Application.version 'folders' don't exists yet.

Do I have to create them first?

Also, I'm testing it on a 64b Win version so I think if I want to check the registry for the key added I have to specifically check the 32bit registry in: C:\Windows\SysWOW64\regedit.exe don't I?

Best Answer

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");
Related Topic