Working with Windows Registry in C#

The Windows registry is the place where Microsoft Windows operating systems store settings and options. During your past endeavors as a programmer, I am sure you ran into numerous situations where working with registry was either necessary or just helpful. In this article, we are going to learn how to accomplish this task in C#.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 10
March 05, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

C# is the simple, modern, general-purpose, and object-oriented programming language developed by Microsoft. Thanks to C#, working with registry is an easy task once you know the basics. First, we will present the structure of the registry in order to refresh our memories. Then we will move on to learning the strategy required to work with it.

Therefore, you can expect to read about how to read, write, and delete specific keys (subkeys) and values. The techniques will be accompanied with appropriate code samples for the purpose of exemplification. We are going to approach this task using the Microsoft.Win32 namespace because it contains the powerful Win32_Registry WMI class (Windows Management Instrumentation - link for Wikipedia entry on WMI), which represents the Windows registry.

I know you are already anxiously waiting to begin, so here we go now!

The Basics

Before we begin, I'd like to point something out: during this tutorial, I will assume that you, the reader, are already familiar with the Windows registry and know most of its "inner workings." Going over details to describe its structure is beyond the scope of this article. Therefore, we are just going to remind ourselves of its structure in a nutshell.

The Windows registry contains the following two elements: keys and values. Each of the keys can also have values and subkeys. Keys act like folders (branches) from an analogical perspective, while values are name-data pairs that actually contain data on their data part. The entire registry is split into various sections that are called hives.

Let's refresh our memory, in case we've forgotten their full or abbreviated names:

Ø        HKCR    --    HKEY_CLASSES_ROOT

Ø        HKCU    --    HKEY_CURRENT_USER

Ø        HKLM    --    HKEY_LOCAL_MACHINE

Ø        HKU      --    HKEY_USERS

Ø        HKCC    --    HKEY_CURRENT_CONFIG

The time couldn't be better for you to launch the Windows Registry Editor (regedit.exe or regedt32.exe) and go over it. Due to the nature of this tutorial, we cannot move on before I suggest that you back up your registry. Once this step is done and you are familiar with its structure, you should be prepared.

It would be very useful for you to create a test key with test values somewhere deep in the hierarchy of the registry. For the purpose of this article, I have created the following subkey: "HKCUSoftwareTutorial" and there I have created a few string values, such as "DS" - "Developer Shed" and "DA" - "Dev Articles."

That's all great. I am sure you have guessed that we are going to work with these values throughout this article. So once you have created the appropriate subkey and string values and your registry is backed up (but we won't do any harm anyway) then please head on to the next page.

Let's Do It!

The guideline for every programming article is to do first things first. Launch  Visual Studio and create a new C# console application project. I myself am using the VS2005. As soon as this step is completed, let's begin coding. You need to add the following line at the end of the namespace declarations. We need the Microsoft.Win32 namespace.

using Microsoft.Win32;

Now we are allowed to use the Registry and RegistryKey classes. The first stands for just the root keys, such as HKCR, HKCU, HKLM, HKU, and HKCC. The latter represents all the subkeys of the selected root key. This is important because we can't work explicitly with the root-key, since it is read-only and also a critical part of the Windows registry. So what we do is access the rootkey and then work with its subkeys.

RegistryKey regkey = Registry.CurrentUser;

regkey = regkey.OpenSubKey("SoftwareTutorial");

The above code snippet creates a new regkey object that selects the HKCU root-key. Then we proceed to use the OpenSubKey() method, which opens the explicitly specified subkey (SoftwareTutorial); notice that we use double backslashes (you can avoid the use of double backslashes if you type an @ sign prior to the argument). The method returns null if, for whatever reason, the desired subkey cannot be found.

As always we need to do some error handling. To avoid the latter scenario, we use the following if condition:

if (regkey == null)

{

      Console.WriteLine("Couldn't open the desired subkey.");

      return;

}

At this stage, I hope that you haven't skipped a step in the previous section where we created our test subkey titled "Tutorial" in HKCUSoftware and that you have also added some values to it. If you failed to do so, then please stop for a moment and do it now. Once you are ready, we are going to continue writing another code snippet that reads and prints out all of the name-data pairs from our Tutorial subkey.

The code attached below starts with a method called GetValueNames(). It does nothing but retrieve an array of strings that contain all the value names associated with this key. Basically, think of it like retrieving all of the names from the name-data pair. Now glance below and check out the snippet.

string[] valnames = regkey.GetValueNames();

int i = 0;

foreach (string s in valnames)

{

      string val = (string)regkey.GetValue(valnames[i++]);

      Console.WriteLine(s + " contains " + val);

}

As you can see we have accomplished this task using the GetValue() method. It retrieves the value that is associated with the name you desire (argument). Just for clarification, the valnames is a string that contains the name of each name-data pair that's located in our subkey. In my case, it contains DS, AF, SC, DA, DH. Using the GetValue() method, we retrieve the data that's associated with each of them.

It is useful to get into the habit of always closing your registry object because it also flushes its contents in case it has been modified. This is a great practice and I can guarantee that being memory efficient is always an advantage. That's why we are now going to close that regkey object and then launch our console application.

regkey.close();

Here we are launching our registry manipulation application for the first time. In my case, I've got the following output (attached below). However, keep in mind that this depends on the name-data pairs that you've created in the specific Tutorial subkey.

DS contains Dev Shed

AF contains ASP Free

SC contains SEO Chat

DA contains Dev Articles

DH contains Dev Hardware

Oh, and to convince you that indeed I've got these values in my Tutorial subkey, I am attaching the following screen shot directly from Regedit:

You might be wondering what specifies their sequence and why they have been listed that way, or more appropriately, why DS, AF, SC, DA, and DH is their order. Well, that's how I created those name-data pairs. Microsoft's very own Regedit lists them in alphabetical order.

By now you should be able to read from the Windows registry. That's great! The next step is learning how to write to the registry. To accomplish this, we are going to use the method called CreateSubKey(), which works in exactly the same fashion as OpenSubKey(). For the purpose of this article we are going to work in the same Tutorial subkey.

regkey = Registry.CurrentUser;

regkey = regkey.CreateSubKey("SoftwareTutorialNewSubKey");

Here we have created and accessed our newly created NewSubKey subkey located in HKCUSoftwareTutorial. After this step, we are going to create two new name-data pairs in NewSubKey. We do this using the SetValue() method.

regkey.SetValue("TestValueName", "Our Value");

regkey.SetValue("AnotherTestValue", "Second Value");

Now if we attach the code snippet that retrieves and prints out all of the values from our subkey once again, then these two will also appear. Here's the output:

TestValueName contains Our Value

AnotherTestValue contains Second Value

Finally, we have learned how to read from and write to the Windows registry. Now we need to clarify two more things: modification and deleting. That's what the next page covers. There you'll also find a few smart tricks. And we'll move on to wrap up everything that we've just learned throughout this tutorial. The entire source code is also going to be attached for you to download, if you had difficulty following the instructions.

More Techniques

We haven't really discussed the details of the OpenSubKey() method. On the previous page, it accessed the subkey only in read-only mode. That's because it has two overloads. The first only specifies which key to open; in this case, it opens and returns the subkey as read-only. However, we can add another bool parameter (boolean - true or false) that explicitly specifies the desired write mode.

If we want to modify the contents of an existing subkey, we use it accordingly:

regkey = Registry.CurrentUser;

regkey = regkey.OpenSubKey("SoftwareTutorial", true);

Of course, we cannot forget about error handling, but that has already been covered previously. Next, we are going to modify the data value of one of our values located in HKCUSoftwareTutorial. I have chosen the "DS" value and changed its data from "Dev Shed" to "Edited Dev Shed." We do this using the SetValue() method. Follow along:

regkey.SetValue("DS", "Edited Dev Shed");

regkey.Flush();

Notice that I've also added the Flush() method, which writes all of our modifications to the registry. This is important in case you want to peek into your Windows registry with regedit to see whether the modifications were successfully completed. The SetValue() method works like this: you specify the name of the value that's going to be modified and then the new data for that value. It's that simple.

After this stage, you can print out all of the values located in our Tutorial subkey using the technique presented before. In my case, the output was the following:

DS contains Edited Dev Shed

AF contains ASP Free

SC contains SEO Chat

DA contains Dev Articles

DH contains Dev Hardware

Now comes the deleting part. We are going to introduce three new methods. The first is DeleteSubKey(). It deletes the specified subkey. The second is DeleteSubKeyTree(). It's yet again self-explanatory because it deletes the specified tree of subkeys. The last one is DeleteValue(),which obviously deletes the specified value. Check out their syntax below.

public void DeleteSubKey(string subkey);

public void DeleteSubKeyTree(string subkey);

public void DeleteValue(string name);

Let the fun begin! We are going to "destroy" our Tutorial subkey by deleting a value from it first, then deleting the NewSubKey located in Tutorial subkey, and then complete this process by deleting our entire Tutorial subkey as a whole.

Here's the code segment. This won't be included in the attached source code sample because it would delete everything (only the Tutorial subkey, in fact) at the end.

regkey = Registry.CurrentUser;

regkey = regkey.OpenSubKey("SoftwareTutorial", true);

regkey.DeleteValue("DS");

regkey.DeleteSubKey("NewSubKey");

regkey.Close();

regkey = Registry.CurrentUser;

regkey = regkey.OpenSubKey("Software", true);

regkey.DeleteSubKeyTree("Tutorial");

regkey.Close();

As you can see from the block of code above, the deleting process was done in two stages. First we opened the HKCUSoftwareTutorial subkey in writable mode and then deleted the DS value and its NewSubKey subkey. After this, we closed it and reopened it again in writable mode, but now as its parent subkey, HKCUSoftware. And then using the DeleteSubKeyTree() method, we removed our Tutorial subkey in its entirety.

We have just finished learning how to read, write, modify, and delete from/to the registry. This means that we are prepared to "work" and manipulate with the Windows Registry any time. Here I am attaching the sample source code in a fully commented format, so it helps you understand and grasp the specific concepts. Hope it helps!

Final Words

You see, we've come to the end of this tutorial. Give yourself a pat on the back because now you can read, write, modify, and delete from/to the Windows Registry. This is very useful knowledge to have in a coder's arsenal because the things you can do with the registry are almost limitless.

Please do understand that this tutorial article mainly targets the beginner or intermediate programmer-- generally C# coders are familiar with the syntax of the language, but haven't had the chance to work with the registry yet. Therefore, I have started almost from the beginning, but leaped ahead assuming that the reader is able to follow along. It doesn't target the pros.

All kinds of settings and information about the operating system are stored in the registry, starting with file associations, usernames, and directory paths, all the way up to system policies and the specific details of any installed software. Whether you are designing a stand-alone application that works on Windows or just writing a simple script for administrative purposes, you can bet that working with the registry could make your job easier.

If you still have unanswered questions or are facing some programming issues, then don't hesitate to join our community at "DevHardware Forums" or any other forum in the Shed network that specializes in coding, such as the "DevShed Forums." Our communities are friendly and we're doing our best to help. See you there.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials