Click here to Skip to main content
Click here to Skip to main content

Working with Windows Registry using VB.NET

By , 28 Mar 2003
Rate this:
Please Sign up or sign in to vote.

Introduction

Developers have always found the windows registry to be a suitable place for storing application specific information and configuration settings. Traditionally, the registry has been used for storing configuration information like database connection strings, profiles etc. The popularity of the registry can be attributed to the fact that registry access is faster than file access and also because it is a very secure system-wide data repository. Moreover, configuration files like INI files had their own limitations.

In this article I shall discuss some basics of Windows registry and then explain how basic registry operations can be done in VB.NET

Basics of Windows Registry

The registry is organized as a hierarchical structure. It has basically five predefined keys under which all data is added or accessed. These keys cannot be renamed or deleted. Given below is a table containing a brief description about them.

Subtree

Definition

HKEY_CURRENT_USER

This contains configuration information of a user who is currently logged on to the system.That is, user profile data is stored here

HKEY_USERS

Contains all user profiles on the computer. HKEY_CURRENT_USER is actually an alias for a key in the HKEY_USERS sub tree.

HKEY_LOCAL_MACHINE

Contains configuration information particular to the computer, irrespective of which user is logged on.

HKEY_CLASSES_ROOT

Contains data that associates file types with programs, and configuration data for COM objects.

HKEY_CURRENT_CONFIG

Contains information about the hardware profile used by the local computer at system startup.

Each key has many subkeys and may have a value. Given below is a snapshot of the registry as seen through the registry editor (Regedit.exe), which comes along with windows.

Registry Structure

Fig 1: Registry Structure

In the snapshot shown above, each node under My Computer is a key. For example , HKEY_CURRENT_CONFIG is a key which has two subkeys: Software and System. Fonts is a subkey under software and has values. Each Value contains a name and its associated data. Each value needs to be associated with a particular data type. Given below is a table containing the important data types

Data types

Used for

REG_SZ

A fixed-length text string. Boolean (True or False) values and other short text values usually have this data type.

REG_EXPAND_SZ

A variable-length text string that can include variables that are resolved when an application or service uses the data.

REG_DWORD

Data represented by a number that is 4 bytes (32 bits) long.

REG_MULTI_SZ

Multiple text strings formatted as an array of null-terminated strings, and terminated by two null characters.

Referring back to figure 1, there is a value called LogPixels which has data of type REG_DWORD and value 96.

Working with Microsoft.Win32 Namespace

The operations on the registry in .NET can be done using two classes of the Microsoft.Win32 Namespace: Registry class and the RegistryKey class.The Registry class provides base registry keys as shared public (read-only) methods: 

ClassesRoot

This field reads the Windows registry base key HKEY_CLASSES_ROOT.

CurrentConfig

Reads the Windows registry base key HKEY_CURRENT_CONFIG.

CurrentUser

Reads the Windows registry base key HKEY_CURRENT_USER

LocalMachine

This field reads the Windows registry base key HKEY_LOCAL_MACHINE.

Users

This field reads the Windows registry base key HKEY_USERS.

Each of the public methods shown above provides an object of the RegistryKey class whose methods can be used to access subkeys under the corresponding keys. The important members of the RegistryKey class are enlisted below

Public Properties

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

Close

Closes the key and flushes it to disk if the contents have been modified.

CreateSubKey

Creates a new subkey or opens an existing subkey.

DeleteSubKey

Deletes the specified subkey.

DeleteSubKeyTree

Deletes a subkey and any child subkeys recursively.

DeleteValue

Deletes the specified value from this key.

Flush

Writes all the attributes of the specified open registry key into the registry.

GetSubKeyNames

Retrieves an array of strings that contains all the subkey names.

GetValue

Retrieves the specified value.

GetValueNames

Retrieves an array of strings that contains all the value names associated with this key.

OpenSubKey

Retrieves a specified subkey, with the write access as specified.

SetValue

Sets the specified value.

VB.NET and Registry

I shall now come to the practical aspect and see how the registry can be manipulated using VB.NET code. I have considered three basic operations: Creating a subkey, adding values and deleting a subkey

Creating a Subkey

Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", True)
regKey.CreateSubKey("MyApp")
regKey.Close()

In the code snippet shown above, I have created a subkey under HKLM\Software called MyApp. Note that I passed True as the second parameter to the OpenSubKey method. This boolean value is to indicate whether the key is writable or not. For instance, you can set it to false if you are just reading data from the registry.

Reading and Writing Values

Dim regKey As RegistryKey
Dim ver As Decimal
regKey = Registry.LocalMachine.OpenSubKey("Software\MyApp", True)
regKey.SetValue("AppName", "MyRegApp")
ver = regKey.GetValue("Version", 0.0)
If ver <  1.1 Then
regKey.SetValue("Version", 1.1)
End If
regKey.Close()

In the code snippet shown above, I am creating two values AppName and Version. I am also setting the values to MyRegApp and 1.1 respectively. Note: If you recollect that in the previous sections I had mentioned about data types for registry values like REG_SZ. But nowhere in the above code we mentioned about the data type. This is because .NET runtime interprets the type itself based on what is passed as value and we do not need to pass it explicitly.

Deleting a Subkey

Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("Software", True)
regKey.DeleteSubKey("MyApp", True)
regKey.Close()

In the code snippet shown above, I am deleting the subkey MyApp and all its values. Note that in the call to DeleteSubkey, I have passed a second Boolean argument of True. This means that an exception is thrown when the key to be deleted is not found

Important

  • To read and write to the registry you need security permissions. If you do not have sufficient permissions, then you will get a SecurityException when you try to access or create keys.
  • The registry is a very sensitive part of the Windows Operating system. So, it is imperative that you take a backup of the registry before attempting to play around with it. A corrupt registry could render the operating system non functional.

Conclusion

This article hopefully has made it easier for beginners to understand the registry and to do simple operations with it. A lot more operations are possible with the Registry and RegistryKey classes but for the sake of simplicity, I have omitted all those here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Manoj G
Web Developer
India India
I am a software developer and have worked on Microsoft technologies for about five years now. I have always been fascinated by Microsoft technologies and with the advent of .NET , this fascination has reached new heights. I take a lot of interest reading technical articles and equally enjoy writing them. I really like to be called a .NET junkie and will surely try to live up to this name Smile | :)
 
I am .NET MVP and have also completed MCAD, MCSD(VS 6), MCDBA (SQL Server 2000), MCSA (Win 2K) and MCTS (Distributed Apps) certfications.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 394439728-Jul-12 21:03 
GeneralMy vote of 5 PinmemberMember 394817030-May-11 2:00 
GeneralMany Thanks. PinmemberSchudi30-Mar-11 0:50 
GeneralRegistry key Time Pinmembersnehalpatil22-Mar-11 0:09 
GeneralGood one Pinmemberjeal4real20-Jul-10 1:19 
QuestionChanging Desktop Appearance PinmemberGomda16-Apr-09 7:34 
GeneralProblem Generate while Pinmembereg_Anubhava5-Feb-09 20:54 
Questionplz help me Pinmemberagrawal nilesh19-Oct-08 21:38 
GeneralMouse Sensitivity Pinmemberneedmoney973@yahoo.com20-Jun-08 11:05 
Generalwriting to registry PinmemberPrajakta joshi18-Jun-08 0:13 
GeneralRead Value & Name of Binary Type Pinmembersonia.sardana27-May-08 3:36 
GeneralDelete Registry key on Uninstall PinmemberPradeep Sattikar17-Oct-07 23:26 
QuestionREG_DWORD PinmemberJangoL18-May-07 20:04 
GeneralGetRegistry PinmemberSolanki Rajat8-Apr-07 21:16 
GeneralREG_BINARY Pinmemberryan_tan_cy1-Feb-07 21:23 
GeneralRe: REG_BINARY PinmemberMatrixCoder14-Mar-07 15:29 
GeneralRe: REG_BINARY Pinmembermr.nelson17-Jul-07 4:27 
GeneralRe: REG_BINARY Pinmemberhacksign237-Sep-08 16:57 
GeneralHi Manoj Pinmembervalueclix24-Jan-07 20:08 
QuestionHow do you Load a Key into HKEY_USERS ? Pinmemberguayony1-Jan-07 9:58 
QuestionIs this what i would use to delete IE history PinmemberSimon North27-Nov-06 11:17 
GeneralDon't forget! PinmemberYep-ItsMe4-Aug-06 12:44 
GeneralVersion. PinmemberPrabhurajan21-Jun-06 20:50 
GeneralTake care registry settings during deployment PinmemberSujo John9-Jun-06 6:27 
In my program to take care of fetching alphanumeric values from excel sheet I want to change the registry values ImportMixedTypes = "Text" and TypeGuessRows =0 in HKEY-LOCAL-MACHINE -> SOFTWARE->Microsoft->Jet->4.0->Engines->Excel.
 
It is possible in development machine.But I need to deploy the executables in different systems where the registry changes for each and every system is impossible.
Do you have any solution regarding this?Pls help me ASAP........
 
Sujo
GeneralIs there is a method to save a subkey to file PinmemberTiefa4-Feb-06 16:18 
GeneralRegistry PinmemberKaushik Baruah16-Oct-05 20:45 
QuestionHow to Set Datatype of a Key PinmemberMuhammad Waqas Butt18-Aug-05 22:10 
AnswerRe: How to Set Datatype of a Key Pinmembermr.nelson17-Jul-07 4:29 
GeneralRegistry Browse PinmemberShrim31-Jan-05 23:53 
GeneralIs it possible to create a key in HKEY_USERS PinmemberJigar Mehta5-Aug-04 1:57 
GeneralRe: Is it possible to create a key in HKEY_USERS PinmemberThe_Mega_ZZTer23-Sep-05 16:40 
GeneralProblem with the sample PinmemberCorobori18-Apr-04 14:00 
Generalhelpful for beginners Pinmembernoby_datasoft15-Apr-04 16:50 
GeneralRegistry functions with Compact Framework PinsussMichael Gledhill26-Sep-03 0:22 
GeneralRe: Registry functions with Compact Framework PinsussMichael Gledhill26-Sep-03 1:19 
GeneralSecurity Permisions PinmemberRicardoLP1-Apr-03 23:54 
GeneralRe: Security Permisions PinmemberManoj G6-Apr-03 0:27 
GeneralRe: Security Permisions PinsussHAVM00728-Oct-04 3:13 
GeneralRe: Security Permisions PinmemberThe_Mega_ZZTer23-Sep-05 16:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 29 Mar 2003
Article Copyright 2003 by Manoj G
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid