Introduction
This article shows you how to code a class for reading and writing to the Windows Registry using VB.NET. This class has proven to be useful in several of my projects.
The Registry
Along with the release of Windows 95, the concept of the Registry was introduced. The Registry is one of the Windows architecture components. It replaces the old .INI files that were used to store important information about applications in previous versions of Windows. For example, each application could have its .INI file to store the initial dimensions and position of its main window, user names and passwords used, the last four files that were opened, and all sort of preferences and settings. There were mounds of .INI files everywhere. So, Windows 95 implemented the Registry, a central and unique location to store all the system and application settings.
The Registry is compounded by six keys (five in Windows NT/2000 and XP because these Operating Systems don't have the Hkey_Dyn_Data
key). Two of these six keys are basic, the other four are derived from these two (in fact they are aliases of the other two). The organization of the Registry is represented by the following figure:
Fig. 1 - Hierarchy of the Windows Registry
To check this, you can go to the Start button of Windows, click Run ..., then type regedit and press Enter. The Registry Editor will appear. In the left panel, you will see the six keys I was talking about.
Fig. 2 - Registry Editor
Each key starts with the word HKEY, which stands for Key Handle. We are going to call these keys, key roots. Each key root has subkeys. Each key root is related to one aspect of the configuration data, like the user or computer-dependent settings.
HKEY_CLASSES_ROOT
: This branch of the Registry contains all the names of the registered file types and their properties. In other words, the information saved here ensures the right program opens when you double-click a file in Windows Explorer. This key is an alias of the HKEY_LOCAL_MACHINE\Software
subkey.
HKEY_CURRENT_USER
: This key contains the configuration information about the user who is currently logged on. The user profile is stored here: user's folders, screen colors and Control Panel settings. This branch is an alias of the HKEY_USERS
key.
HKEY_LOCAL_MACHINE
: Contains configuration information related to the computer for all users.
HKEY_USERS
: This branch stores all the user profiles on the computer.
HKEY_CURRENT_CONFIG
: This key has information about the hardware profile used by the local computer at system startup.
HKEY_DYN_DATA
: This key is available only in Windows 9x/ME. Some information in Windows 98 must be stored in the RAM because it requires fast modification and can't wait for the Registry to flush to the hard disk. All this data can be found under this key root. This branch is an alias of Hkey_Local_Machine \Configs
.
Coding the class CRegistry
GetSetting
and SaveSetting
are functions that allow you to read and write to the Registry. But they only let you read and write in the HKEY_CURRENT_USER\Software\VB
and VBA
keys. In your projects, you may want to write where the pros do: in HKEY_CURRENT_USER\Software\
. Hence we won't use these functions, but a fantastic object from Win32 that knows no limit. Let's see.
First, you import the Microsoft.Win32
namespace. This allows you to use the Registry
object which represents the Windows Registry and its methods for handling its basic operations. You know the class will have properties and methods, the properties are going to be the six main keys described above, the values of which you can access for specifying the path you need to read or write to. The methods we need will be the following: one for creating a subkey (or several nested subkeys) inside any of the main keys, one for deleting a subkey, one for writing, one for reading, and one for deleting data in the Registry.
Well, here are the public properties. Since you are likely to use them from outside the class - for passing the full path of your settings - these have to be public.
Public ReadOnly Property HKeyLocalMachine() As RegistryKey
Get
Return Registry.LocalMachine
End Get
End Property
Public ReadOnly Property HkeyClassesRoot() As RegistryKey
Get
Return Registry.ClassesRoot
End Get
End Property
//..and so on until you have the six keys
//.
//.
Public ReadOnly Property HKeyDynData() As RegistryKey
Get
Return Registry.DynData
End Get
End Property
Let's get into the methods. We are going to write the CreateSubKey
method, which we will use for creating new subkeys inside any of the six main keys in the Registry.
Public Function CreateSubKey(ByVal ParentKey As RegistryKey, _
ByVal SubKey As String) As Boolean
Try
ParentKey.CreateSubKey(SubKey)
Return True
Catch e As Exception
Return False
End Try
End Function
Now, you may be wondering how to use this method. Let's suppose you want to create another subkey inside the HKEY_LOCAL_MACHINE\Software
subkey, which is actually the path where software vendors store their application's settings. If you run the Registry Editor again and take a look at this subkey (HKEY_LOCAL_MACHINE\Software
), chances are you will find a plethora of subkeys, each one with the name of a software firm, like Adobe, Apple Computer, McAfee, Microsoft, Novell, etc. So let's create our very own software brand subkey inside, like MySoftCorp
. The only thing you got to do is throw a couple of lines like these:
Dim objReg As New CRegistry
objReg.CreateSubKey(objReg.HKeyLocalMachine, "Software\MySoftCorp")
After this call, there should be a new subkey inside HKEY_LOCAL_MACHINE\Software
called MySoftCorp
. All our methods are going to return True
if they are successful, otherwise they return False
. Here you can create more subkeys, one for each application. If your company develops two applications, an accounting app and a stock market app, each application should install its own subkey inside HKEY_LOCAL_MACHINE\Software\MySoftCorp
. For example, you would have HKEY_LOCAL_MACHINE\Software\MySoftCorp\AccountingApp
and HKEY_LOCAL_MACHINE\Software\MySoftCorp\
StockMarketApp
. We could also create more than one subkey at once if we call the method like this:
objReg.CreateSubKey(objReg.HKeyLocalMachine, _
"Software\MySoftCorp\AccountingApp")
The second method is for deleting a subkey. The code is as follows:
Public Function DeleteSubKey(ByVal ParentKey As RegistryKey, _
ByVal SubKey As String) As Boolean
Try
ParentKey.DeleteSubKey(SubKey, False)
Return True
Catch e As Exception
Return False
End Try
End Function
We already have the mechanisms to create all the subkeys we need, but we need to write a method for creating and storing values inside a subkey. Look into any subkey, for example HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion
. You can see a bunch of values in the right panel. Each value has a name, a type, and data. The possible data types are the following: REG_SZ
(can be a string or boolean), REG_EXPAND_SZ
(variable length text string), REG_DWORD
(a 32-bit integer), or REG_MULTI_SZ
(array of text strings). To create a new value name and assign a value to it, we need the key, the subkey(s), the name of the value we want to create, and the value itself (data). Here is the code for the WriteValue
method:
Public Function WriteValue(ByVal ParentKey As RegistryKey, _
ByVal SubKey As String, _
ByVal ValueName As String, _
ByVal Value As Object) As Boolean
Dim Key As RegistryKey
Try
Key = ParentKey.OpenSubKey(SubKey, True)
If Key Is Nothing Then Key = ParentKey.CreateSubKey(SubKey)
End If
Key.SetValue(ValueName, Value)
Return True
Catch e As Exception
Return False
End Try
End Function
Note: we declared Value
as Object
in the parameters of the method so that we can pass a string or a numeric value and the call to Key.SetValue()
will write the value using the matching data type in the Registry. Therefore we are not required to specify which data type our value is going to be. Cool, huh? Check this example for creating a string or a numeric value:
Dim strUsrName As String = "Sinhue"
objReg.WriteValue(objReg.HKeyLocalMachine, _
"Software\MySoftCorp\StockMarketApp", _
"UserName", strUsrName)
Dim intMaxDocs As Integer = 10
objReg.WriteValue(objReg.HKeyLocalMachine, _
"Software\MySoftCorp\StockMarketApp", _
"MaxDocsOpened", intMaxDocs)
Next I'm going to show you a method for reading data from a value. As you will see, the parameters are the same. We're going to return the data in the Value
parameter, which is declared as a parameter by reference.
Public Function ReadValue(ByVal ParentKey As RegistryKey, _
ByVal SubKey As String, _
ByVal ValueName As String, _
ByRef Value As Object) As Boolean
Dim Key As RegistryKey
Try
Key = ParentKey.OpenSubKey(SubKey, True)
If Key Is Nothing Then Throw New Exception("the subkey doens't exist")
End If
Value = Key.GetValue(ValueName)
Return True
Catch e As Exception
Return False
End Try
End Function
Finally, we're going to add a method for deleting a value name:
Public Function DeleteValue(ByVal ParentKey As RegistryKey, _
ByVal SubKey As String, _
ByVal ValueName As String) As Boolean
Dim Key As RegistryKey
Try
Key = ParentKey.OpenSubKey(SubKey, True)
If Not Key Is Nothing Then
Key.DeleteValue(ValueName)
Return True
Else
Return False
End If
Catch e As Exception
Return False
End Try
End Function
Conclusion
Well, that's all there is to it. I have provided you with source code for the class, plus a method for getting all the subkeys inside a given subkey. I converted this class into a DLL that I add to my projects whenever I want to access the Windows Registry. Undoubtedly, there are plenty of improvements that could be made to the code. I hope you find it useful as much as I have.