How to Write into Windows Registry in C# 5.0

Developing a real application almost everytime requires the storing of some important values in the Windows Registry. The Windows Registry gives the power to store variables of different types by any application and use them as and when required. You can also store values in the form of texts, external files or saved documents then why use the Registry? Because the Registry allows above all the values to be stored and read in a standardized way which can be read by compatible applications as and when required. Also, the deletion of corresponding files does not alter the information in the Windows Registry. The contents have to be modified explicitly to delete or modify existing values.

The windows registry can be modified using the C# programming interface. In this section we shall see how to write to a known location in the windows registry. The Windows registry consists of different locations in an explorer style and looks as shown below:



The Keys at the parent level are HKEY_CLASSES_ROOT, HKEY_CURRENT_USER etc. When we refer to these keys in our C# program code, we omit the HKEY & the underscores. So, to refer to the HKEY_CURRENT_USER, we use simply CurrentUser as the reference. Well, this reference is available from the Microsoft.Win32.Registry class. This Registry class is available through the reference:
  • using Microsoft.Win32;
.We use this reference to create a Key object. An example of a Key object would be:
  • Microsoft.Win32.RegistryKey key;
Now this key object can be set to create a Subkey in the parent folder. In the example below, we have used the CurrentUser as the parent folder:
  • key = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("CSharp_Website");
Next we can set the Value of this Field using the SetValue() funtion. See below:
  • key.SetValue("Really", "Yes!");
The output shown below:


As you will see in the picture below, you can select different parent folders(such as ClassesRoot, CurrentConfig etc.) to create and set different key values: