How to Read, Write, and Delete from the Windows Registry with C#

Operating System

It’s a common requirement for a software developer to have to access the Windows Registry. Many applications store their settings within the registry, not to mention Windows itself. So in this article I will show you how to do this, and also how to create and delete registry keys.

Although many applications use the registry for storing their settings and configurations, nowadays it’s not the recommended practise any more. Instead you should store your application’s settings in an XML file – such as the Settings.settings file in your C# project. If you don’t know what the Settings.settings file is I wrote an article on it which you can read here – Using the Settings file in C#.

Before you start testing any code which manipulates the registry be sure you know exactly what you’re editing. Changing, or even worse, deleting registry keys and values which are used by Windows can cause it to fail to load, and you would have to try to restore Windows back or maybe even reinstall it completely. So don’t say you haven’t been warned!

On the positive side, the registry manipulation we will be looking at in this article will not affect Windows so it is quite safe if you follow my examples.

The Registry and the RegistryKey Classes

These are the classes we will be using to manipulate the registry. They are both found under the Microsoft.Win32 namespace so you will have to add it to your project to use the classes.

The Registry class provides us with objects that represent the root keys in the Windows registry. It also contains static methods to access key and value pairs but we will not be using these in this article. The root key representations are as follows:

Registry Value Class Property
HKEY_CLASSES_ROOT Registry.ClassesRoot
HKEY_CURRENT_CONFIG Registry.CurrentConfig
HKEY_CURRENT_USER Registry.CurrentUser
KEY_DYN_DATA Registry.DynData
HKEY_LOCAL_MACHINE Registry.LocalMachine
HKEY_PERFORMANCE_DATA Registry.PerformanceData
HKEY_USERS Registry.Users

 

The RegistryKey class represents a key-level node in the Windows registry and this is the class we will be making the most use of.

Creating Keys and Values

So let’s start by creating a RegistryKey object which represents HKEY_LOCAL_MACHINE.

// Create an instance of HKEY_LOCAL_MACHINE registry key
RegistryKey parentKey = Registry.LocalMachine;

Next we are going to create another RegistryKey object which represents the SOFTWARE key found under HKEY_LOCAL_MACHINE. We are passing true as the second parameter to the OpenSubKey method. This is to indicate that we require write access on that registry key. If we pass false, the key will be read only.

// Open the SOFTWARE registry sub key under the HKEY_LOCAL_MACHINE parent key
RegistryKey softwareKey = parentKey.OpenSubKey("SOFTWARE", true);

Next we are going to create our own key under the SOFTWARE key. For this example I called it DaveOnC#.

// Create a DaveOnC# registry sub key under the SOFTWARE key
RegistryKey subKey = softwareKey.CreateSubKey("DaveOnC#");

Now let’s add a few values to our sub key DaveOnC#. Let’s add a name value and two other values for storing URLs and set their value type to string.

// Add values to DaveOnC# sub key
subKey.SetValue("Name", "David Azzopardi", RegistryValueKind.String);
subKey.SetValue("WebsitePrimary", "http://www.daveoncsharp.com", RegistryValueKind.String);
subKey.SetValue("WebsiteSecondary", "http://www.daveoncsharp.net", RegistryValueKind.String);

If you have got to this point, once you open a registry editor tool such as regedit.exe, you will be able to see the key DaveOnC# we created and if you click on that key you will see the three values we just created as well.

Registry Key Values

Now let’s create a sub key under the DaveOnC# key, and let’s call it “Top Articles”.

// Create a Top Articles registry sub key under the DaveOnC# key
RegistryKey articlesSubKey = subKey.CreateSubKey("Top Articles");

Next we’ll add a few values to the Top Articles key. As you will see in the below code, we are not passing RegistryValueKind.String to the SetValue method this time. This is because the SetValue assumes the value is of type string when no RegistryValueKind is passed as a parameter, so we can avoid typing it.

Personally I would take the extra effort and type it in full. There are two main reasons why I would do this:

  1. It makes the code easier to read because nothing is open to interpretation since everything is written down.
  2. If Microsoft ever decide to change the default value type, or the meaning of the parameters accepted by the SetValue method, the code will fail on compilation and not at runtime, therefore making it easier to spot the error. It is highly unlikely this will happen though.
// Add values to Top Articles sub key
articlesSubKey.SetValue("The MessageBox Explained", "http://www.daveoncsharp.com/2009/06/the-messagebox-explained/");
articlesSubKey.SetValue("File Comparison in C# – Part 1", "http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-1/");
articlesSubKey.SetValue("File Comparison in C# – Part 2", "http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-2/");
articlesSubKey.SetValue("File Comparison in C# – Part 3", "http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-3/");
articlesSubKey.SetValue("C# Chat Application Over Asynchronous UDP Sockets – Part 1, The Server", "http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1/");
articlesSubKey.SetValue("C# Chat Application Over Asynchronous UDP Sockets – Part 2, The Client", "http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-2/");
articlesSubKey.SetValue("Create a Screen Saver Using C# – Part 1", "http://www.daveoncsharp.com/2009/08/create-a-screen-saver-using-csharp-part-1/");
articlesSubKey.SetValue("Create a Screen Saver Using C# – Part 2", "http://www.daveoncsharp.com/2009/08/create-a-screen-saver-using-csharp-part-2/");

If you were to look at the registry again (from regedit.exe) you will now see that we have a new sub key under DaveOnC# called Top Articles, and it contains the values we just created above.

If you export the DaveOnC# key from regedit.exe you should end up with something like this:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\DaveOnC#]
"Name"="David Azzopardi"
"WebsitePrimary"="http://www.daveoncsharp.com"
"WebsiteSecondary"="http://www.daveoncsharp.net"

[HKEY_LOCAL_MACHINE\SOFTWARE\DaveOnC#\Top Articles]
"The MessageBox Explained"="http://www.daveoncsharp.com/2009/06/the-messagebox-explained/"
"File Comparison in C# – Part 1"="http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-1/"
"File Comparison in C# – Part 2"="http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-2/"
"File Comparison in C# – Part 3"="http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-3/"
"C# Chat Application Over Asynchronous UDP Sockets – Part 1, The Server"="http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1/"
"C# Chat Application Over Asynchronous UDP Sockets – Part 2, The Client"="http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-2/"
"Create a Screen Saver Using C# – Part 1"="http://www.daveoncsharp.com/2009/08/create-a-screen-saver-using-csharp-part-1/"
"Create a Screen Saver Using C# – Part 2"="http://www.daveoncsharp.com/2009/08/create-a-screen-saver-using-csharp-part-2/"

Deleting Keys and Values

To delete a value is quite straight forward. Let’s delete the WebsiteSecondary value from the DaveOnC# key.

// Delete the WebsiteSecondary value
subKey.DeleteValue("WebsiteSecondary");

Now let’s delete all that we have created so far:

// Delete the parent registry key
softwareKey.DeleteSubKeyTree("DaveOnC#");

And if you open regedit.exe again you will see that all the work you just did has vanished :). It is that easy to delete a registry key with all its values! So imagine how easy it is to delete something by mistake… be careful when deleting from the registry.

Finally, we must remember to close all the RegistryKey objects we created.

// Close RegistryKey objects             
articlesSubKey.Close();
subKey.Close();
softwareKey.Close();
parentKey.Close();

Accessing the Registry in Windows Vista

Because of the added security features in Windows Vista you cannot access the registry by just using the above code. You must add an app.manifest file to your application. I explained how to use the requestedExecutionLevel section of the manifest file in my previous post – Writing To The Windows Event Log Using C#, so you can have a look towards the end of that article if you want to know a little bit more about the manifest file.

What’s important for this example is that we must edit the requestedExecutionLevel section in the manifest file to look like the below, so that our application will run with administrative rights under an administrator account:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

And that brings us to the end of this article.

If you liked this article subscribe to my full feed rss so that you will receive new articles automatically in your rss reader. Also, please feel free to leave your comments below or if you want you can contact me directly from my Contact Page.

Stay tuned for more articles soon.

Dave

8 comments… add one
  • Great post. This is a great introduction on how to interface with the windows registry using c#.

    • Thanks for your comment Steve – I’m glad you found it interesting.

      • nethra Link Reply

        can you please tell me how to write registry values into xml file

  • unam Link Reply

    sir its a great post,
    i would like to ask u small question?

    by following your instructions, now i am able to add text to reg file successfully, but i would like to add text through GUI editor.

    I have created GUI app, in that i added textbox1 nd textbox2. by using these textbox i would like to add some notes to reg file, could you please help me out.

    looking forward.

  • Srini Link Reply

    wonderful article 🙂

  • SM Link Reply

    Very clearly explained and with great examples! Congratulations!

  • I still like this article after all this time. Something to point out for deleting the subkeytree that I dont see shown here. i had to modify OpenSubKey before deleting DaveOnC#. That might not occur to someone right off the bat. Just sharing. Still, short and excellent article.

    RegistryKey parentKey = Registry.CurrentUser;
    RegistryKey softwareKey = parentKey.OpenSubKey(“SOFTWARE\\WinRegistry”, true);
    softwareKey.DeleteSubKeyTree(“DaveOnC#”);

  • SusanSS Link Reply

    I tried to translate some of your code into VB.net for WinForms.
    “Adding a key” works perfectly.
    But nothing I try works to “delete that same key”.

    Here’s the “add key”:
    Const g_RegKey As String = “HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\”
    Const g_RegValue As String = “MyKey”
    My.Computer.Registry.SetValue(g_RegKey, g_RegValue, Application.ExecutablePath)

Leave a Comment