Registry Access in .NET

What Is a Registry?

A Registry is a database repository for information about a computer's configuration. The Registry contains information that Windows continually references during operation, such as:

  • Profiles for each user.
  • The programs installed on the computer and the types of documents each can create.
  • Property settings for folders and program icons.
  • What hardware exists on the system.
  • Which ports are being used.

The Registry is organized hierarchically as a tree and is made up of keys and their sub keys, hives, and value entries.


In the Registry Editor, a key is a folder that appears in the left pane of the Registry Editor window. A key can contain sub keys and value entries. For example, Environment is a key of HKEY_CURRENT_USER.

Sub key

A sub key is a key within a key. In the Registry structure, sub keys are subordinate to sub-trees and keys. Keys and sub keys are similar to the section header in .ini files; however, sub keys can carry out functions.

Predefined key

A key that represents one of the main divisions of the Registry. Each predefined key is displayed in a separate Registry Editor window, with the key's name appearing in the window's title bar. For example, HKEY_CLASSES_ROOT is a predefined key.

Value entry

The string of data that appears in the right pane of a Registry window and that defines the value of the currently selected key. A value entry has three parts: name, data type, and the value itself.


A section of the Registry that appears as a file on your hard disk. The Registry sub-tree is divided into hives (named for their resemblance to the cellular structure of a beehive). A hive is a discrete body of keys, sub keys, and values that is rooted at the top of the Registry hierarchy. A hive is backed by a single file and a .log file, which are in the systemroot\System32\Config or the systemroot\Profiles\username folders.

By default, most hive files (Default, SAM, Security, and System) are stored in the systemroot\System32\Config folder. The systemroot\Profiles folder contains the user profile for each user of the computer. Because a hive is a file, it can be moved from one system to another. However, you must use the Registry Editor to edit the file.


The path and folder name where the Windows system files are located. Typically, this is C:\Windows, although you can designate a different drive or folder when you install Windows. You can use the value %systemroot% to replace the actual location of the folder that contains the Window system files. To identify your systemroot folder, click Start, click Run, type %systemroot%, and then click OK.

Overview of Some Predefined Keys and Data Types in the Registry

Folder/Predefined Key Description
HKEY_CURRENT_USER Contains the root of the configuration information for the user who is currently logged on. The user's folders, screen colors, and Control Panel settings are stored here. This information is referred to as a user's profile.
HKEY_USERS Contains the root of all user profiles on the computer. HKEY_CURRENT_USER is a sub key of HKEY_USERS.
HKEY_LOCAL_MACHINE Contains configuration information particular to the computer (for any user).
HKEY_CLASSES_ROOT Is a sub key of HKEY_LOCAL_MACHINE\Software. The information stored here ensures that the correct program opens when you open a file by using Windows Explorer.
HKEY_CURRENT_CONFIG Contains information about the hardware profile used by the local computer at system startup.

The following table lists the data types currently defined and used by the system.

Data Type Description
REG_BINARY Raw binary data. Most hardware component information is stored as binary data and is displayed in the Registry Editor in hexadecimal format.
REG_DWORD Data represented by a number that is 4 bytes long. Many parameters for device drivers and services are this type and are displayed in the Registry Editor in binary, hexadecimal, or decimal format.
REG_EXPAND_SZ A variable-length data string. This data type includes variables that are resolved when a program or service uses the data.
REG_MULTI_SZ A multiple string. Values that contain lists or multiple values in a form that people can read are usually this type. Entries are separated by spaces, commas, or other marks.
REG_SZ A fixed-length text string.
REG_FULL_RESOURCE_DESCRIPTOR A series of nested arrays designed to store a resource list for a hardware component or driver.

A brief history of the Registry

The concept of the Registry has been in existence only since Windows 95, the first GUI OS from Microsoft. Prior to that, the system information was stored in the form of INI files. Whenever software or hardware is installed, an INI file is automatically created; it stores the information about the installed hardware/software. The drawback of this system is that there is no centralized information available and the number of files in the system folder increases considerably.

Why Registry access?

A question may arise in the minds of programmers: Why do we need to access the Registry from our applications? The answer is:

  • If you need to retrieve some system information
  • If you want to maintain state information of your application, and so forth.


Case 1:

If you want to retrieve the Windows directory of the current system, you will have to use the API function GetWindowsDirectory. This function takes information from the Registry and gives it to you. In every system, Windows may not be necessarily installed on the C: drive and the path need not be necessarily C:\Windows or C:\Winnt. Therefore, hard-coding of this path will lead to invalid results.

Case 2:

Consider your application has provisions to change its environment settings like back color, fore color, and so on. You want the settings made in the previous session to be reflected automatically when you restart the application the next time. This will be impossible unless the information is stored physically somewhere outside the application and retrieved from there every time the application starts. The best and safer place to store this is in the Windows Registry.

You also can store the state information in an INI file created from the application, storing it in a predefined path and manipulating it whenever required. If different sets of information are needed to be stored separately, file maintenance becomes tedious. Login information also can be stored in the Registry and retrieved every time.

Registry Access Facilities in .NET

There are built-in classes in .NET that provide facility to access the Windows Registry from within your application.

Registry is a built-in class that helps in manipulating a Registry. RegistryKey is another class that helps manipulate a key in the Registry. By using these classes, one can access the Windows Registry in an easy and efficient manner. They have an exhaustive collection of built-in attributes and methods that facilitate the Registry manipulations.

On the other hand, Win32 APIs also could be used to manipulate the Windows Registry. This method is applicable for Visual Basic 6 also. There are separate functions for creating, opening, closing, and deleting keys and storing, retrieving, and modifying values of a key.

Registry Access in .NET

Classes for Registry Access

There are two major classes used in .NET to access the Windows Registry. To use them, you need to import the Microsoft.Win32 namespace.

Registry Class

Supplies the base Registry keys that access values and sub keys in the Registry.

The base (root) RegistryKey instances that are exposed by the Registry delineate the basic storage mechanism for sub-keys and values in the Registry. The keys are all read-only because the Registry depends on their existence. The keys exposed by Registry are:

  • CurrentUser: Stores information about user preferences.
  • LocalMachine: Stores configuration information for the local machine.
  • ClassesRoot: Stores information about types (and classes) and their properties.
  • Users: Stores information about the default user configuration.
  • PerformanceData: Stores performance information for software components.
  • CurrentConfig: Stores non-user-specific hardware information.
  • DynData: Stores dynamic data.

Once you have identified the root key under which you want to store/retrieve information from the Registry, you can use the RegistryKey class to add or remove sub-keys, and manipulate the values for a given key.

Hardware devices can place information in the Registry automatically by using the Plug and Play interface. Software for installing device drivers can place information in the Registry by writing to standard APIs.

Public Fields

Field Description
ClassesRoot Defines the types (or classes) of documents and the properties associated with those types. This field reads the Windows Registry base key HKEY_CLASSES_ROOT.
CurrentConfig Contains configuration information pertaining to the hardware that is not specific to the user. This field reads the Windows Registry base key HKEY_CURRENT_CONFIG.
CurrentUser Contains information about the current use'sr preferences. This field reads the Windows Registry base key HKEY_CURRENT_USER
DynData Contains dynamic Registry data. This field reads the Windows Registry base key HKEY_DYN_DATA.
LocalMachine Contains the configuration data for the local machine. This field reads the Windows Registry base key HKEY_LOCAL_MACHINE.
PerformanceData Contains performance information for software components. This field reads the Windows Registry base key HKEY_PERFORMANCE_DATA.
Users Contains information about the default user configuration. This field reads the Windows Registry base key HKEY_USERS.

RegistryKey Class

Represents a key level node in the Windows Registry. This class is a Registry encapsulation.

Registry Keys are the base unit of organization in the Registry, and can be compared to folders in Windows Explorer. A particular key can have sub-keys (just as a folder can have subfolders), and can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key, or the level directly under the base keys. Each key also can have multiple values associated with it (a value can be compared to a file), which are used to store the information about the application you are interested in. Each value holds one particular piece of information, which can be retrieved or updated when required. For instance, you can create a RegistryKey for your company (under the key HKEY_LOCAL_MACHINE\Software), and then a sub-key for each application that your company creates. Each sub-key holds the information specific to that application such as color settings, screen location and size, or recognized file extensions.

Public Properties

Property Description
Name Retrieves the name of the key.
SubKeyCount Retrieves the count of subkeys at the base level, for the current key.
ValueCount Retrieves the count of values in the key.

Public Methods

Method Description
Close Closes the key and flushes it to disk if the contents have been modified.
CreateObjRef (inherited from MarshalByRefObject) Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
CreateSubKey Creates a new subkey or opens an existing subkey. The subKey string is not case sensitive.
DeleteSubKey Overloaded. Deletes the specified subkey. The string subKey is not case sensitive.
DeleteSubKeyTree Deletes a subkey and any child subkeys recursively. The string subKey is not case sensitive.
DeleteValue Overloaded. Deletes the specified value from this key.
Equals (inherited from Object) Overloaded. Determines whether two Object instances are equal.
Flush Writes all the attributes of the specified open Registry key into the Registry.
GetHashCode (inherited from Object) Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService (inherited from MarshalByRefObject) Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetSubKeyNames Retrieves an array of strings that contains all the subkey names.
GetType (inherited from Object) Gets the Type of the current instance.
GetValue Overloaded. Retrieves the specified value.
GetValueNames Retrieves an array of strings that contains all the value names associated with this key.
InitializeLifetimeService (inherited from MarshalByRefObject) Obtains a lifetime service object to control the lifetime policy for this instance.
OpenRemoteBaseKey Opens a new RegistryKey that represents the requested key on a foreign machine.
OpenSubKey Overloaded. Retrieves a specified subkey, with the write access as specified.
SetValue Sets the specified value.
ToString Overridden. Retrieves a string representation of this key.

Protected Methods

Method Description
Finalize Overridden. Closes the key and flushes it to disk if the contents have been modified. In C# and C++, finalizers are expressed using destructor syntax.
MemberwiseClone (inherited from Object) Creates a shallow copy of the current Object.



Imports Microsoft.Win32    'Namespace Required for Accessing Registry

Dim regKey As RegistryKey, regSubKey As RegistryKey

'A Procedure to create a key and Write a value into the key

Public Sub WriteToRegistry
   'regKey now points to HKEY_CURRENT_USER Registry Key
   regKey = Registry.CurrentUser
   'A Sub key called MyProgram is created under the
   regSubKey =regKey.CreateSubKey ("MyProgram")
   'The value of the Key is set to VeryGoodSetting
   regSubKey.SetValue ("MyValue", "VeryGoodSetting")
End Sub

'A Procedure to Open a key and read values from it

Public Sub ReadFromRegistry
   regKey = Registry.CurrentUser
   regSubKey = regKey.CreateSubKey ("MyProgram")
   MsgBox (regSubKey.GetValue ("MyValue"))
End Sub


using Microsoft.Win32;

RegistryKey regKey, regSubKey;

public void WriteToRegistry
   regKey = Registry.CurrentUser;
   regSubKey =regKey.CreateSubKey ("MyProgram");
   regSubKey.SetValue ("MyValue", "VeryGoodSetting");

public void ReadFromRegistry
   regKey = Registry.CurrentUser;
   regSubKey = regKey.CreateSubKey ("MyProgram");
   Console.WriteLine (regSubKey.GetValue ("MyValue"));


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • It's no secret what keeps CIOs up at night. Mobile, cloud, data, security, and social have become the "five imperatives," the drivers of business progress, innovation, and competitive differentiation. Business leaders around the world want to hear how other companies are succeeding. How are they applying the latest technologies? How did they get started? What outcomes are they achieving? Read this online magazine for success stories from organizations like the NBA, Pfizer, and San Jose State University as they …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds