Joydip Kanjilal
Contributor

How to access the Windows Registry using C#

opinion
May 20, 20164 mins
Software Development

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

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(@"SOFTWAREIDG");

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(@"SOFTWAREIDG"))

           {

               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 = @"SOFTWAREIDG";

           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);

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author