Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to registry in a C# application

Tags:

c#

registry

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?

like image 517
PeeHaa Avatar asked Aug 29 '11 12:08

PeeHaa


People also ask

How do I write in the registry editor?

In the search box on the taskbar, type regedit, then select Registry Editor (Desktop app) from the results. Right-click Start , then select Run. Type regedit in the Open: box, and then select OK.

Is a 1 or a 0 true in the registry?

Each URL that is filtered is listed in the Registry with a value of either 0 or 1 (the x value). An entry of 0 indicates that the URL is not cached and 1 indicates that the URL is cached. The y value is the TTL in minutes. This is an optional value that can be set only by editing the Registry.

What is registry key in C#?

You can consider registry keys are folders in your windows system. Note that a key can have sub keys - much the same way a folder can contain sub folders inside it. To work with the Windows Registry using C#, you can take advantage of the Registry class in the Microsoft. Win32 namespace.


1 Answers

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"); 
like image 158
Silx Avatar answered Sep 19 '22 13:09

Silx