Developer

Manipulate the Windows registry with .NET

The Windows registry can be used to store application data for any custom applications you may develop. Learn more about interacting with the registry via .NET in Tony Patton's column.

The registry is an integral part of every Windows installation. It contains a wealth of information regarding operating system configuration along with the hardware and installed software. Programmatic access to the registry in the pre-.NET days involved working with the Windows API. The .NET Framework simplifies the process with the Microsoft.Win32 namespace. This article takes a closer look at working with the registry in .NET.

Registry overview

The Windows registry is organized in a tree or hierarchical structure. Windows provides the registry editor to work with it (regedt32.exe/regedit/exe). The registry consists of keys that comprise all data. These keys may not be deleted or renamed. The following list provides an overview of these keys:

  • HKEY_CURRENT_USER: The root of the configuration information for the currently logged on user. The user's folders, screen colors, and Control Panel settings are stored within this key (aka, the user's profile). It is a subkey of HKEY_USERS.
  • HKEY_USERS: This key contains the root of all user profiles on the computer.
  • HKEY_LOCAL_MACHINE: This key contains configuration information for the computer.
  • HKEY_CLASSES_ROOT: This key contains file association information; that is, it tells Windows what program to use to open specific file types. It is a subkey of HKEY_LOCAL_MACHINE\Software.
  • HKEY_CURRENT_CONFIG: This key contains information on the computer's hardware.
  • HKEY_PERFORMANCE_DATA: Each software component creates keys for its objects and counters when it is installed and writes counter data while it is executing. This performance data is stored within this key.
Weekly .NET tips in your inbox
TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET.
Automatically sign up today!

Within these keys, data may be stored in various ways. There are six data types used to store data within the registry. These types are outlined in the following list:

  • REG_BINARY: Binary data is stored as a string of hex pairs where each pair gives a range of 0 to 255. REG_BINARY can be any length.
  • REG_DWORD: The double word data type is a four-byte number (32-bits) with values ranging from 0 to 4GB. Device drivers and services parameters are often of this type.
  • REG_EXPAND_SZ: The expandable string data type is actually a variable. When used, the value is replaced by the real value when the string is called by the system.
  • REG_MULTI_SZ: A multiple string value with the different values separated by spaces, commas, and other characters.
  • REG_SZ: A fixed-length text string value.
  • REG_FULL_RESOURCE_DESCRIPTOR: Used in hardware registry keys.

With this basic knowledge of the registry, you can take advantage of the appropriate .NET classes to work with the contents of the registry.

Working with the registry

The Microsoft.Win32 namespace provides the necessary classes to work with the Windows registry. The two main classes within the namespace are the Registry and RegistryKey. The Registry class is used in conjunction with the RegistryKey class to access individual registry keys. It maps to the main registry keys outlined earlier:

  • Registry.CurrentUser
  • Registry.Users
  • Registry.LocalMachine
  • Registry.ClassesRoot
  • Registry.CurrentConfig
  • Registry.PerformanceData

The RegistryKey class is used to access individual registry keys using one of the Registry class items in the previous list. The following C# Windows application code displays information for a specific entry in the ClassesRoot registry key.

RegistryKeyrootKey = Registry.ClassesRoot;
rootKey = rootKey.OpenSubKey(".doc", true);
MessageBox.Show(rootKey.GetValue("").ToString());
MessageBox.Show(rootKey.GetValue("Content Type").ToString());
foreach(string sub in rootKey.GetSubKeyNames()) {
MessageBox.Show(sub);
RegistryKeytmp = rootKey.OpenSubKey(sub);
MessageBox.Show(tmp.Name);
}
foreach(string test in rootKey.GetValueNames()) {
MessageBox.Show(rootKey.GetValue(test).ToString());
}

The code references the proper namespace to utilize the registry classes:

using Microsoft.Win32;

The code accesses the specific subkey within the ClassesRoot key (.doc). The key defines how files with the specified file extension (.doc) are handled by the system. The first two message box statements display the information attached to the key itself. The empty value passed to the GetValue method of the RegistryKey class displays the Default Value key. The second message box displays the content type associated with the key (MIME type).

The first foreach block displays the names of all subkeys contained within the registry key. The second foreach block displays the same information as the first two message box statements, but uses the GetValueNames method to achieve the same results (so you don't have to know the name of the item).

The equivalent VB.NET code follows:

Dim rootKey As RegistryKey
rootKey = Registry.ClassesRoot
Dim regSubKey As RegistryKey
Dim subk As String, test As String
Dim tmp As RegistryKey
rootKey = rootKey.OpenSubKey(".doc", True)
MessageBox.Show(rootKey.GetValue("").ToString())
MessageBox.Show(rootKey.GetValue("Content Type").ToString())
For Each subk In rootKey.GetSubKeyNames()
MessageBox.Show(subk)
tmp = rootKey.OpenSubKey(subk)
MessageBox.Show(tmp.Name)
Next
or Each test In rootKey.GetValueNames()
MessageBox.Show(rootKey.GetValue(test).ToString())
Next

Note: Subkey names are not case sensitive.

Adding registry values

Reading registry values is good, but there may be times when you need to add values to the registry. Often, applications use the registry as a central repository for application-specific data. This approach is acceptable, but changes to a Windows system or other application values are not advised to avoid system or application problems.

The RegistryKey class includes the CreateSubKey method to add subkeys to the specific registry key element. In addition, the SetValue method allows you to add items and values to the keys. The following example adds a subkey to the specified key with the HKEY_CLASSES_ROOT key. The addition of the blank value to the key sets its default value.

RegistryKeyrootKey = Registry.ClassesRoot;
RegistryKeyregSubKey;
rootKey = rootKey.OpenSubKey(".doc", true);
regSubKey = rootKey.CreateSubKey ("Newsletter");
regSubKey.SetValue("Site", "www.techrepublic.com");
regSubKey.SetValue("", "Test Link");

The equivalent VB.NET code follows:

Dim rootKey As RegistryKey
rootKey = Registry.ClassesRoot
Dim regSubKey As RegistryKey
rootKey = rootKey.OpenSubKey(".doc", True)
regSubKey = rootKey.CreateSubKey("Newsletter")
regSubKey.SetValue("Site", "www.techrepublic.com")
regSubKey.SetValue("", "Test Link")

The DeleteSubKey method makes it easy to remove keys, so we can remove the newly created subkey without any problems as the following VB.NET code does:

Dim rootKey As RegistryKey
rootKey = Registry.ClassesRoot
rootKey = rootKey.OpenSubKey(".doc", True)
rootKey.DeleteSubKey("Newsletter")

In addition, the DeleteSubKeyTree method allows you to delete a subkey and any child subkeys recursively.

Proceed with caution

There is no Windows component more important than the registry. For this reason, you should use extreme caution when working with its contents because inadvertent changes to system or application keys can cause system or application failure. However, the registry can be used as a storage location for application-specific data for any applications you may develop. Thankfully, the .NET Framework makes it easy to work with the registry regardless of the language used.

Miss a column?

Check out the .NET Archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox