Search:

Custom Search
_________________________________________________________________

Thursday, June 19, 2008

Writing Registry keys

We saw before how to read a registry key. Writing is similar and also accomplished by the RegistryKey object. C# .Net provides very easy methods under this object to write keys.

Be aware that the registry is a key part of an Operating System so you should know exactly what you are doing before actually doing it. Check every single line of the code written. On this example I’ll show you below, I will create a couple of keys with its proper folder too. By doing this I can be sure that any other registry key would be overwritten.

Take a look now at this example:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace WritingRegKeys
{
class Program
{
static void Main(string[] args)
{

RegistryKey RegKeyWrite = Registry.CurrentUser;
RegKeyWrite = RegKeyWrite.CreateSubKey
("Software\\MySoftware\\SubKeys");
RegKeyWrite.SetValue("Try", "True");
RegKeyWrite.SetValue("NumberValue", 1);

RegKeyWrite.Close();

RegistryKey RegKeyRead = Registry.CurrentUser;
RegKeyRead = RegKeyRead.OpenSubKey("Software\\MySoftware\\SubKeys");
Object regTry = RegKeyRead.GetValue("Try");
Object regNumber = RegKeyRead.GetValue("NumberValue");
RegKeyRead.Close();
Console.WriteLine("Try value: " + (String)regTry + " - - NumberValue: " + regNumber);

}
}
}

You can see that after creating the RegistryKey object I also created a subkey with the CreateSubKey method. This will generate another “subfolder” under MySoftware.

The Complete root is: HKEY_CURRENT_USER\Software\MySoftware\SubKeys.

With the RegKeyWrite.SetValue you have to specify the name of that key and the actual values you want to be stored. You can see that the fist value to be stored is a String and the second a Numeric value.

You can try this by reading the keys created above. That why the RegKeyRead Object is also created. Then we just open the SubKey and ask the values for the Try key and the NumberValue key. Run the code and the Console should look something like this:

When you execute the code, a new registry should be created. So let’s take a look at the registry to see if this is true. Open regedit to see the changes.


No comments: