Category : C# | Author : Chtiwi Malek | First posted : 3/9/2012 | Updated : 12/6/2012
Tags : windows, registry, c-sharp,c#,.net,
Create and read a key in the registry using C#

Create and read a key in the registry using C#

In this article we will programmatically create a key in the current user's registry and add a value pair under that key using the .net framework (C#). We will be using the Microsoft.win32 Namespace to access and manipulate the system registry.

The following code will create a key in the current user registry and add a key/value pair, if the key already exist it will be updated:
// Create subkey 'CodiCode' and a value pair “testKey”,”123123”
Microsoft.Win32.RegistryKey rkey;
rkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("CodiCode");
rkey.SetValue("TestKey", "123123");
rkey.Close();
Then we will read the key and get the key/value pair added previously. If the key does not exist OpenSubKey method will return a null object and if the GetValue function dont find the "TestKey", it will return an empty string.
// Reading the key value
Microsoft.Win32.RegistryKey rkey;
rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("CodiCode");
if (rkey == null) {
  // the Key does not exist
}
else {
  string myTestKey = (string)rkey.GetValue("TestKey");
}
Here’s a view from the Microsoft Registry Editor :



Remember that the key value cannot be longer that 255 characters and that storing passwords or other sensitive informations in the registry is not secure, even if the key is protected by ACL  “access control lists”.
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :