How to access the Windows Registry using C#

Explore ways to program the Windows Registry using C# to store and retrieve configuration information

Registry

Registry

Microsoft .Net enables you to access the Windows Registry programmatically to store and retrieve data. The Windows Registry is a hierarchical database that comprises of a collection of Keys, Sub Keys, Predefined Keys, Hives, and Value Entries and can be used to store system specific or application specific data. The MSDN states: "The registry acts as a central repository of information for the operating system and the applications on a computer."

You can take advantage of the Windows Registry to store configuration metadata of your applications so that you can retrieve them at a later point of time if need be.

The Windows Registry stores the following types of information in a hierarchical manner.

  1. User profile information
  2. Hardware information of your system
  3. Property settings
  4. Information on installed programs in your system

Note that you should be extra careful when manipulating the Windows Registry. It is advisable to back-up your registry before you make any changes so that you can revert those changes back if need be. You can create a backup of your Windows Registry by following these steps.

  1. From Start, select Run
  2. Type Regedit and press Enter to invoke the Windows Registry Editor
  3. Now click File -> Export
  4. In the "Save As" dialog specify a name
  5. Select a particular branch or the “All” option to export the entire registry information
  6. Click Save

Your registry information will be saved in a .reg file having the name you specified. You are now safe to manipulate your registry database programmatically.

Working with the Windows Registry in C#

You can programmatically read, write, and delete keys, sub keys and values from the Windows Registry. 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.

Let’s now dig into some code. In this section we will explore how we can create, read or delete subkeys from the Windows Registry using C#.

To create a new sub key you can take advantage of the CreateSubKey method as shown below.

Registry.CurrentUser.CreateSubKey(@"SOFTWARE\IDG");

The CreateSubKey method creates a new sub key and returns it - the return type is RegistryKey. The following code snippet shows how you can create a new sub key named IDG and store key - values inside it.

using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\IDG"))

           {

               key.SetValue("Key 1", "Value 1");

               key.SetValue("Key 2", "Value 2");              

               key.Close();

           }  

The following method can be used to read a value from a sub key.

static string ReadSubKeyValue(string subKey, string key)

       {

           string str = string.Empty;

           using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(subKey))

           {

               if (registryKey != null)

               {

                   str = registryKey.GetValue(key).ToString();

                   registryKey.Close();

               }

           }

           return str;

       }

The ReadSubKeyValue method accepts a subkey and a key as a parameter and returns the value out of it. Here's how you can call the ReadSubKeyValue method.

static void Main(string[] args)

       {

           string subKey = @"SOFTWARE\IDG";

           string str = ReadSubKeyValue(subKey, "Key 1");

           Console.WriteLine(str);

           Console.Read();

       }

You can also delete a sub key using the DeleteSubKey static method. The following code listing illustrates how you can do this.

static bool DeleteKey(string KeyName)

       {

           try

           {

               Registry.CurrentUser.DeleteSubKey(KeyName);

               return true;

           }

           catch

           {

               return false;

           }

       }

The above method returns true if deletion of the sub key is a success, false otherwise. You may want to check if the sub key exists before you attempt to delete it – that way the changes of exceptions being thrown are minimal. I leave it to you to modify the above code to incorporate this change.

You can also retrieve all the sub keys of a particular key using the GetSubKeyNames method of the RegistryKey class. The following code snippet illustrates how this can be achieved.

static List<string> GetChildSubKeys(string key)

       {

           List<string> lstSubKeys = new List<string>();

           try

          {

               using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(key))

               {

                   if (!(registryKey == null))

                   {

                       string[] temp = registryKey.GetSubKeyNames();

                       foreach (string str in temp)

                       {

                           lstSubKeys.Add(str);

                       }

                   }

               }

           }

           catch

           {

               //Write your custom exception handling code here

           }

           return lstSubKeys;

       }

To use the GetChildSubKeys method and retrieve all sub keys of a particular key, you can write the following code.

List<string> lstSubKeys = GetChildSubKeys(subKey);

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.