The Windows Registry...

Modifying the Windows Registry using VB.NET.


By: Brian Mains Date: May 21, 2004 Download the code.

If you've ever been to a Toy's R Us store (or most major department stores), you’ve probably seen the baby, gift, or wedding registry programs that they offer, where the parents/children take a scanning device around the store and select products that they want/need for the upcoming event. Once all the items are registered in the system, anybody that wants to purchase an item on the list can go to the store and have it printed out for them. The registry contains items broken down by aisle (1A, 4B, 13C, etc), which each row has any number of items broken down by vendor name, product name, and product details. After the items are selected and purchased, the items are removed from the registry in the system.

The registry works in a similar manner. Each key (aisle) contains additional subkeys (vendor name and product name). Each key can have any number of subkeys, which can have any number of subkeys, and so on. The keys can also have any number of string, binary, or DWORD values (product details) as desired.

.NET implements registry features through the System.Win32 namespace. The RegistryKey object represents a single key in the registry. To traverse the tree, the RegistryKey must start from one of the root nodes. Below is a list of available root nodes in the registry.


Figure 1: Root nodes in the Registry

Each of these root nodes is accessible through a shared/static property in the Registry class, which returns a RegistryKey object representing this node. From this key value, subkeys can be added, deleted, or traversed using the CreateSubKey, DeleteSubKey and OpenSubKey methods:

Dim objKey As RegistryKey = Registry.LocalMachine
'Creates the MyKey key beneath the software key
objKey.CreateSubKey("Software\MyKey")
'Traverses the Software key to the MyKey key;
'returns a RegistryKey object
objKey.OpenSubKey("Software\MyKey")
'Deletes the MyKey key beneath the software key
objKey.DeleteSubKey("Software\MyKey")

Values within a key are retrieved and manipulated through the SetValue, DeleteValue, and GetValue keys. Any key can have any number of string, binary, or DWORD values associated with it. In addition, the value names can be retrieved through the GetValueNames method, which returns a string array of the value names associated with the current key. The syntax for these methods is:

'Sets the Test value in the MyKey key
objKey2.SetValue("Test", "My Test Value")
'Gets the value for the MyKey key; If no value exists,
'the second parameter is a default value that is returned
Response.Write(objKey2.GetValue("Test", "No value exists, return this"))
'Loop through all of the key names
For Each strValue As String In objKey2.GetValueNames()
  Response.Write(strValue)
Next
'Delete the value from the key
objKey2.DeleteValue("Test")

Let's look at a practical example of using the registry in an application. Let's start by creating the registry settings. Click the Start button and choose "Run"; type "regedit" in the textbox. This brings up the registry editor. If you are unfamiliar with it, it is very similar to the windows explorer window. Expand the HKEY_LOCAL_MACHINE node and the SOFTWARE node. Right-click the SOFTWARE node and select New > Key. Rename the key to "RegistrySiteTest". We've created the key; now we need two values. Right-click the key and select New > String Value. There will be two values needed, one called IsAdministratorsOnly and IsUnderMaintenance. The purpose of these will be discussed later. Add these keys, and upon creation, double-click each one. A prompt will appear; enter the value False in the textbox. These fields will hold Boolean values in a string format, which this string will be converted back to a Boolean value in code.


Figure 2: RegistrySiteTest values

The previous steps are necessary for the code attached to this article. Those values are used to alter the application's state. When either one is set to true, the application is no longer available. In the code below, an exception is thrown if one of the values is set to true; however, in the real world, when the IsUnderMaintenance value is set to True, the application could display a construction page, and the IsAdministratorsOnly value could allow only administrators to access the site.

To use these values in code, a StateManager class was created with two shared/static properties, making these registry values available to the site. Everytime the properties are accessed, the registry is checked. This can pose a performance issue, and so the values of the class can be stored and accessed through a Boolean shared/static variable.

'This class retrieves the values from the registry when requested.
Public Class StateManager
  Public Shared ReadOnly Property IsAdministratorsOnly() As Boolean
    Get
      'Get the RegistrySiteTest under the Local Machine's software key
      Dim objKey As RegistryKey = Registry.LocalMachine.OpenSubKey("Software\RegistrySiteTest", False)
      'Parse the string value into a boolean value
      Return Boolean.Parse(objKey.GetValue("IsAdministratorsOnly", False).ToString())
    End Get
  End Property

  Public Shared ReadOnly Property IsUnderMaintenance() As Boolean
    Get
      'Get the RegistrySiteTest under the Local Machine's software key
      Dim objKey As RegistryKey = Registry.LocalMachine.OpenSubKey("Software\RegistrySiteTest", False)
      'Parse the string value into a boolean value
      Return Boolean.Parse(objKey.GetValue("IsUnderMaintenance", False).ToString())
    End Get
  End Property
End Class

The web page that uses it checks to see if one of these values is true, and raises an error on that condition. This may be desired if user-friendly error pages are used; that error-handling web page (specified through the errorPage property of the web form) could also test for these values and display a message stating that the site is under maintenance or is in administrators only mode. In addition, at this step page redirection could be used to forward the user to an "under construction" page.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  'Put user code to initialize the page here
  If (StateManager.IsAdministratorsOnly) Then
    Throw New System.Exception("This site is under administrators only mode. Please try back again later.")
  ElseIf (StateManager.IsUnderMaintenance) Then
    Throw New System.Exception("This site is currently under maintenance. Please try back again later.")
  End If
End Sub

This is a simple use of the registry. Other uses for the registry are:

This is a simple implementation of an application using the registry, but you can see how effective it can be in your applications.

About the Code

The code attached is an ASP.NET project. Please copy the folder to your wwwroot directory in order to use this example. Additionally, you may have to set this project up as an application for the virtual directory. In IIS, right-click the Caching virtual directory, select Properties. Where it says "Application Name", the button next to it should say "Remove". If it doesn't, hit the create button to create the application.

The code above is available in the project attached. The following files have been used for the project:

In addition, this project doesn't use impersonation. To run it successfully, either setup impersonation in the web.config file or give the ASPNET account privileges to the registry value, by right-clicking the "RegistrySiteTest" node in the registry editor, and selecting Permissions. Give the ASPNET account full privileges; although read only will probably suffice.

Please be careful when editing the registry. The Windows operating system and other software installed on your machine requires that certain keys/values are there so the software can operate successfully. Deleting critical registry keys can result in software not working correctly or at all, which may even result in reinstalling the operating system. So please use caution when using the registry editor.