How to Create & Edit Windows Registry in .NET?

In this tutorial, I’m going to go through the code required to edit the Windows registry using C#.  This will include creating new keys and values as well as modifying existing ones.

The Windows registry is used to store all the configuration information relating to Windows setup, user preferences, software installed and the devices. The registry is arranged in a hierarchical tree-like structure and can be viewed using the popular regedit utility.

Each key can contain additional keys or sub-keys (which allow further branching) as well as values that are used to store the actual data. Each registry key may have several values and each value comprises of name-data pair.

For example, a registry key ‘Desktop’ may have values like ‘Wallpaper’, ‘TileWallpaper’, etc. Each value in a key contains the actual data. This data may take several forms ranging from a simple integer value to a user-defined binary object. Each type is represented by a special registry specific type. For example, an integer is represented by REG_DWORD and a string is represented by REG_SZ.

Many applications store their status (information like ‘last file opened in the application’, ‘options selected by the user’, and so on) in registry. We shall also create such an application that stores the background image, foreground colour, size of the window and its position in the registry so that the next time the application is run these selections can be used to build the window.

For accessing the registry we will use the Registry and RegistryKey classes available in the Microsoft.Win32 namespace. Naturally, we will have to add a using statement for this namespace.

RegistryKey skey, tkey, rootkey;

To write anything in registry keys, we must open them. If keys are not created, we must first create them. We would do this in constructor after a call to the InitializeComponent( ) method. Add the following statements to the constructor:

	rootkey=Registry.LocalMachine.OpenSubKey(“SOFTWARE”, true);
	skey = tkey.CreateSubKey(“Settings”);

In a file system, root drives like C:\ or D:\ are the root directories. In the registry, there are root keys called ‘registry hives’ or ‘base keys’. There are seven such registry hives. The Registry class provides seven fields of type RegistryKey representing the seven registry hives. The LocalMachine field represents the HKEY_LOCAL_MACHINE base key. The OpenSubKey( ) method opens the key. Since we have called the method using LocalMachine field, it would open the SOFTWARE key of Local Machine hive. By passing true as the second parameter we have specified that the key is to be opened for writing. Next, we have created the ‘Theme’ sub-key in the SOFTWARE key and ‘Settings’ in the ‘Theme’ sub-key. We have called the CreateSubKey( ) method for this.

Now let us add handlers for the buttons. The b_bitmap_Click( ) handler gets called when the ‘Choose Bitmap’ button is clicked.

 private    void b_bitmap_Click ( object sender, System.EventArgs e )
   file.Filter = “Image Files (*.bmp,*.gif,*.jpg)|*.bmp;*.gif;*.jpg||”    ; 
   if ( file.ShowDialog( ) == DialogResult.OK )
   BackgroundImage = Image.FromFile ( file.FileName ) ;
   skey.SetValue (“Image”, ( string ) file.FileName ) ;

Here, we have displayed the ‘open’ dialog. We have applied a filter so that only image files get displayed. If the user selects file we have changed the background image of the form and also written the file path as data of the ‘Image’ value in the ‘Settings’ sub-key. We have called the SetValue( ) method for writing the data. The SetValue() method takes the value name and data as parameters. The data needs to be typecast in suitable type as the method takes parameter of type object.

The b_color_Click( ) method gets called when clicked on the ‘Choose Color’ button. The handler is given below.

 private void b_color_Click    (object sender, System.EventArgs e )
   if ( color.ShowDialog( ) == DialogResult.OK ) 
   ForeColor = color.Color ;
   skey.SetValue ( “Red”, ( int ) color.Color.R ) ;
   skey.SetValue ( “Green”, ( int ) color.Color.G ) ;
   skey.SetValue ( “Blue”, ( int ) color.Color.B ) ;

Finally add the code to write size and position to the registry. This code should get executed when the window is closed. So, we would add this code in the Dispose( ) method. The Dispose( ) method is given below:

 protected override    void Dispose ( bool disposing )
   skey.SetValue ( “Height”, ( int ) Height ) ;
   skey.SetValue ( “Width”, ( int ) Width ) ;
   skey.SetValue ( “X”, ( int ) DesktopLocation.X ) ;
   skey.SetValue ( “Y”, ( int ) DesktopLocation.Y ) ;
   skey.Close( ) ;
   tkey.Close( ) ;
   rootkey.Close( ) ;
   // AppWizard generated code

After writing the values we have closed the keys by calling the Close( ) method. Now our writing part is over. We want that when the application is executed the next time, the form should get displayed the same way as it was before closing. To read the information from registry, we have written a user-defined method readsettings().

	public void readsettings()
   	rootkey = Registry.LocalMachine.OpenSubKey ( “SOFTWARE”, false ) ;
 		tkey = rootkey.OpenSubKey ( “Theme” ) ;
		if ( tkey == null )
		return ;
		skey = tkey.OpenSubKey ( “Settings” ) ;
		string f = ( string ) skey.GetValue ( “Image” ) ;
		if ( f != null )
		BackgroundImage = Image.FromFile ( f ) ;
			int r = ( int ) skey.GetValue ( “Red” ) ;
			int g = ( int ) skey.GetValue ( “Green” ) ;
			int b = ( int ) skey.GetValue ( “Blue” ) ;
			ForeColor = Color.FromArgb ( r, g, b ) ;
			Height = ( int ) skey.GetValue ( “Height” ) ;
			Width = ( int ) skey.GetValue ( “Width” ) ;
			int x = ( int ) skey.GetValue ( “X” ) ;
			int y = ( int ) skey.GetValue ( “Y” ) ;
			DesktopLocation = new Point ( x, y ) ;
		catch ( Exception e )
			return ;

Here, firstly we have opened the keys. When the application is run for the first time, keys are not created. So, we have checked for the null reference in the RegistryKey object. The statements written thereafter read the data from registry and use it. Call this method from the InitializeComponent() method after the initialisation code.

The registry is a great way to save information between application launches.  Many applications use the registry to save information about dialog sizes and placements.  That way the user doesn’t have to resize and move dialogs every time the program starts.

Let’s start by creating a new registry key.  The first thing we need to decide is where to put our new key.  If you bring up the Registry Editor – type “regedit” in the run bar, you’ll notice the registry looks a lot like a file explorer.  “Computer” is the root node with several child folders branching from it.

Most software packages will have a registry key inside


These keys are available no matter who is logged in and is a good place to stick general application values.  Let’s put a key in this folder called “My Registry Key”.

Registry.LocalMachine.CreateSubKey(“SOFTWARE\\My Registry Key”);

Registry is a class located in the Microsoft.Win32 namespace.  Registry.LocalMachine means where going to be modifying the HKEY_LOCAL_MACHINE registry key.  We passed in “SOFTWARE\\My Registry Key” to CreateSubKey because we wanted our new key created inside the “SOFTWARE” key.  CreateSubKey has the option to take more arguments – mostly dealing with access and security, but they’re not important for this tutorial.

If you open the Registry Editor again, you’ll now see you’re new key.  A key without any values is pretty useless, so let’s add a string value to it.

RegistryKey myKey = Registry.LocalMachine.OpenSubKey(“SOFTWARE\\My Registry Key”, true);
myKey.SetValue(“My String Value”, “Test Value”, RegistryValueKind.String);

The OpenSubKey method is called to get a reference to our newly created key.  It takes the path to the key, which is the same as when creating it, and it takes a boolean indicating whether or not we want to open it writable.  Since we want to add a new value to this key, we want to set this to true.

Next, we simply call SetValue to create our new value.  The SetValue function takes the name of the value as the first argument, the actual value as the second, and the type of value as the third. The RegistryValueKind enumeration has lots of different kinds of data, so most primitive types can be stored in the registry.  If the value you’re trying to set doesn’t exist yet (like in this case), SetValue will create it for you.

Now let’s look at how to get values back out of the registry.  It’s very similar to setting values and equally as easy.

RegistryKey myKey = Registry.LocalMachine.OpenSubKey(“SOFTWARE\\My Registry Key”, false);
string myValue = (string)myKey.GetValue(“My String Value”); //myValue now equals “Test Value”

We get a reference to our key exactly like we did before except this time we pass false for the writable argument.  A call to GetValue is then made to retrieve the value from the registry.  This function returns an object, so it must first be cast to your desired type – in this case string.  It’s always wise to check that the return value is not null before casting it since it is possible that the registry value you’re trying to read doesn’t exist.

Sample Code:
using Microsoft.Win32;
private void button2_Click(object sender, EventArgs e)
MessageBox.Show(“Registry Created!”);
RegistryKey myKey = Registry.LocalMachine.OpenSubKey(“SOFTWARE\\Shekhars_Key”, true);
//SET Initial Value to ZERO

//myKey.SetValue(“My Counter”, “0”, RegistryValueKind.String);

string myValue = (string)myKey.GetValue(“My Counter”);
int cnt=Convert.ToInt32(myValue);
if (cnt != 1000)
myKey.SetValue(“My Counter”, cnt.ToString(), RegistryValueKind.String);

MessageBox.Show(“Dear XYZ! Your Counter is Over…!”);

That’s all the code required to read and write to the Windows registry using .NET and C#.  Leave questions and comments below.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s