(Print this page)

Using the registry from a VB.Net application
Published date: Wednesday, October 1, 2003
On: Moer and Éric Moreau's web site

The registry is that huge repository that store just about anything you want and that you need to open with caution (otherwise your Windows or some applications can refuse to start if you delete invalid hives!).

The registry, when used correctly, can be of great help. Much every application needs to persist some information between sessions. Remember my May 2003 column, which talks about just that? In that article, I have only scratched the surface of the registry. This month, we will get deeper on that topic. We'll see how to add, delete, and read registry settings. All this will be done using the Microsoft.Win32 namespace.

Creating the demo project

If you want to build this demo yourself, start by creating a user interface looking like the image you see here. Don't forget that a complete demo is available for download at the end of this article.

Figure 1: The demo interface.

At the top of the code in your form, you need to add the line to imports the namespace:

Imports Microsoft.Win32

Adding values to the registry

The code needed to create a key into the registry and place some values in it is very simple (this code can be placed into the Click event of a button):

Dim oReg As RegistryKey
oReg = Registry.LocalMachine.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey("UTMagDemo")
oReg.SetValue(txtName.Text, txtValue.Text)
The code starts by opening the Software key of the HKEY_LOCAL_MACHINE registry hive. Notice that all the hives are available (LocalMachine and CurrentUser are probably the ones you will most often use). The second parameter means that you are opening this key and that you will later write in it.

Once the Software key is opened, the UTMagDemo sub key is created in it. If this key already exists, nothing happens. No exceptions are raised. The key content will remain untouched. Notice that you can create a complete hierarchy in a single call (ie oReg.CreateSubKey("UTMagDemo\\Level1\\Level2\\Level3") is correct). Don't ask me why all the backslashes are doubled. Even if you put only one, it will be working. Even a mix of single and double backslashes is working (according to my own tests). It may have something to do with C# since the backslash is an escape character in C# (but has no impact in VB.Net). If you find out why, drop me a line!

The next line adds a new value to the sub key just created. If you let the Name parameter empty (or you set it to Nothing), the value will be saved in the (Default) key name. If you provide a value for a name that exists, the value is simply replaced without warnings.

The last line is closing the key we opened.

Many exceptions may be triggered while trying to write to the registry. The most encountered are:

  • The user does not have permissions to create registry keys. 
  • The key name cannot exceeds 255 characters 
  • The key is closed. 
  • The key is read-only.

Reading the value back

Many of the lines needed to read from the registry are the same as the ones we used to write:

Dim oReg As RegistryKey
Dim strValue As String
oReg = Registry.LocalMachine.OpenSubKey("Software\\UTMagDemo")
strValue = oReg.GetValue(txtName.Text, "DEFAULT-VALUE").ToString
MessageBox.Show(strValue, _
                "Stored Registry Value", _
                MessageBoxButtons.OK, _
The code starts by opening the sub key we created in the previous sample. One thing you really need to check (and it is not done here – but it is done into the downloadable demo) is if the oReg is Nothing after the call of the OpenSubKey method. This indicates that the key you passed to the method does not exist. No exceptions are raised when this occurs.

The following line uses GetValue to retrieve the value with the Name parameter. Again, if you let the Name parameter empty (or you set it to Nothing), the value in the (Default) key name will be retrieved. If the Name does not exist, the default value (if you provide one) will be returned.

The last line is closing the key we opened.

Wiping out our stuff

The Delete method has 3 flavours: 

  • DeleteValue deletes a single value (using the Name parameter to specify which one to delete). 
  • DeleteSubKey deletes a complete key and all the values it contains in a single shot (but raises an exception if it contains sub keys). 
  • DeleteSubKeyTree deletes a complete key and all the values it contains as well as all sub keys in a single shot. The code I use for this demo is the following:
Dim oReg As RegistryKey
oReg = Registry.LocalMachine.OpenSubKey("Software", True)
The recipe is always the same: open the key, delete, close.

For those who want more

Now that we know how to deal with the registry, we can retrieve valuable information stored in it.

In the downloadable demo, I have added another feature that list all the values in the key and all its sub keys (see the message box image for a typical result). See what's hidden behind the "Get Values" button.

Figure 2: Get Values results

Retrieving file type of a file extension

This other example shows how to retrieve the file type from a file extension.

Dim oReg As RegistryKey
Dim strIndexerKey As String
Dim strType As String

'Opens the key to retrieve the class name
oReg = Registry.ClassesRoot.OpenSubKey(txtFileExtension.Text)
If oReg Is Nothing Then
    MessageBox.Show("The file extension " & _
                    txtFileExtension.Text & _
                    " is unknown.", _
                    "File Type", _
                    MessageBoxButtons.OK, _
    Exit Sub
End If
strIndexerKey = oReg.GetValue("").ToString

'Opens the class name to retrieve the file type
oReg = Registry.ClassesRoot.OpenSubKey(strIndexerKey)
strType = oReg.GetValue("", "").ToString
MessageBox.Show("The file extension " & _
                txtFileExtension.Text & _
                " is a " & strType, _
                "File Type", _
                MessageBoxButtons.OK, _

'Close the registry keys.
For example, let's say the txtFileExtension textbox contains .doc, the strIndexerKey will contains something like "Word.Document.8" (that depends on what is installed on your own computer). We can retrieve the file type from that key which is "Microsoft Word Document" in my case. If you look at the code carefully, there is nothing more then we have already seen.


Was it difficult? Not at all when you know the basics! Have fun.

(Print this page)