In todays tutorial we are going to talk a walk-thru of working with the Windows Registry in VB.Net. Working with and manipulating the registry can seem like a daunting task for the first time, but once you dive into it it's not such a scary thing.
NOTE: Manipulating the Windows Registry can have serious adverse affects on your computer. It is always a good idea to backup your registry before making any changes, that way if you do something wrong you have the original to fall back on. To backup your registry follow these steps:
- Click the Start button
- Select Run
- When the Run Dialog opens type regedit and click OK
- When Regedit opens click on File
- Then select Export
- When the Save As dialog opens select where you'd like to save and give it a name
- Under Export Range select the All radio button
- Then click Save
Your Registry is now saved (depending on the size of your registry exporting it can take a couple minutes). Before we jump into working with the Windows Registry, lets take a look at what exactly the Windows Registry is and what it consists of.
The Windows Registry is a repository for a computers configuration, it contains information such as:
- Profiles for each user
- All programs installed on the computer, and their configuration
- Property settings for things like icons, folders, programs to start when Windows start, etc.
- All hardware in the computer
- All ports and what programs/hardware are using them
The Windows Registry is a hierarchal tree, it consists of
Keys,
Sub Keys,
Predefined Keys,
Hives, and
Value Entries. Lets take a look at each of these items:
- Key: A key is a node in the Registry Tree, for example SOFTWARE is a Key of HKEY_LOCAL_MACHINE
- Sub Key: A Sub Key is a Key within a Key, for example Microsoft is a SubKey of SOFTWARE
- Predefined Keys: A Key that represents one of the main sections of the Registry.
There are 5 Predefined Keys in the Windows Registry
- HKEY_CURRENT_USER : Contains the configuration for the currently logged on user
- HKEY_USERS: Contains all loaded user profiles on the computer
- HKEY_CLASSES_ROOT: Stores all information necessary to make sure that the correct program executes when you open a file in Windows Explorer
- HKEY_LOCAL_MACHINE: Contains all configuration information for the computer
- HKEY_CURRENT_CONFIG: Contains all the configuration information for the computer for the currently logged in user
- Hive: A group of keys, sub keys and values in the registry. The 5 Predefined keys are each a Registry Hive
- Value Entries: The value of the sub key in each key
Now that we have a high-level overview of what the registry is, what it contains and it's primary function, lets take a look at some code to manipulate, read from, and write to the Windows Registry. To facilitate working with the Windows Registry I created a Wrapper Class, so I didn't have to retype the same code over and over whenever I needed to work with the Registry. That way all I have to do is add a reference to the DLL and use it in any application I need to (even a C# application).
Before any of these methods will work you will need to add a reference to the
Microsoft.Win32 Namespace. To do this add the following line at the top of your class (by the way, this is a
Class Library Project, not a
Windows Application project)
CODE
Imports Microsoft.Win32
The first thing to learn about working with the Windows Registry is to read information from the registry, the following method allows us to do this.
CODE
''' <summary>
''' Function to read a value from the Registry
''' </summary>
''' <param name="MainKey">RegistryKey -> One of the 6 main level keys you want to write to</param>
''' <param name="sKey">String -> Sub key you want to read</param>
''' <param name="sKeyName">String -> Name of the value you want to read</param>
''' <param name="oNameValue">Object -> The value to be read</param>
''' <returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function ReadRegistryValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String, _
ByRef oNameValue As Object) As String
Dim rkKey As RegistryKey
Dim Value As New String("")
Try
'open the given subkey
rkKey = MainKey.OpenSubKey(sKey, True)
'check to see if the subkey exists
If rkKey Is Nothing Then 'it doesnt exist
'throw an exception
Throw New Exception("The Registry SubKey provided doesnt exist!")
End If
'get the value
oNameValue = rkKey.GetValue(sKeyName)
Value = oNameValue.ToString
Catch e As Exception
MessageBox.Show(ex.Message, "Error: Reading Registry Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return Value
End Function
The next thing you'll want to investigate is writing a value to the Registry, this comes in handy in application installations, you could even use it to store user information. For writing to the Registry I have 2 functions:
- Create a registry Sub Key
- Create a Sub key Value Entry
First you need to create a Sub Key before you can add Value Entries to it
CODE
''' <summary>
''' Function to create a new Sub Key in the Windows Registry
''' </summary>
''' <param name="MainKey">RegistryKey -> One of the 6 main keys to create the subkey in</param>
''' <param name="sKey">String -> Name of the subkey to create</param>
''' <param name="KeyPermissions">RegistryKepPermissionCheck -> Specifies permissions of the SubKey to be created</param>
''' <returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function CreateRegistrySubKey(ByVal MainKey As RegistryKey, ByVal sKey As String, _
ByVal KeyPermissions As RegistryKeyPermissionCheck) As Boolean
Try
'create the new subkey
MainKey.CreateSubKey(sKey, KeyPermissions)
Return True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: Creating SubKey", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
End Function
Now that you've created your Sub Key you can add Value Entries to it using this function.
CODE
''' <summary>
''' Writes a value in the Registry
''' </summary>
''' <param name="MainKey">RegistryKey -> One of the 6 main keys that you want to write to</param>
''' <param name="sKey">String -> Name of the subkey you want to write to. If the subkey doesnt
''' exist it will be created</param>
''' <param name="sKeyName">String -> Name of the value to create</param>
''' <param name="oNameValue">Object -> Value to be stored</param>
''' <param name="RegType">RegistryValueKind -> Data type of the subkey value</param>
''' <returns>True (Succeedeed)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function WriteSubKeyValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String, _
ByVal oNameValue As Object, ByVal RegType As RegistryValueKind) As Boolean
Dim rkKey As RegistryKey
Try
'Open the given subkey
rkKey = MainKey.OpenSubKey(sKey, True)
'check to see if the subkey exists
If rkKey Is Nothing Then 'doesnt exist
'create the subkey
rkKey = MainKey.CreateSubKey(sKey, RegistryKeyPermissionCheck.Default)
End If
'set the value of the subkey
rkKey.SetValue(sKeyName, oNameValue, RegType)
Return True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: Writing Registry Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
End Function
The next aspect of working with the Registry is removing values from the Registry (be careful with this, you really shouldn't be removing values that aren't associated with your application unless you know what you are doing).
This wrapper has 2 delete function:
- Delete a SubKey value
- Delete the SubKey itself
First lets take a look at deleting a Sub Key value. Pass it the Predefined Key, the Sub Key and the Value Entry you want to remove and it removes it for you. If you provide a Sub Key that doesn't exist it displays this error to you.
CODE
''' <summary>
''' Function to delete a subkey value from the Windows Registry
''' </summary>
''' <param name="MainKey">RegistryKey -> One of the 6 main keys you want to delete from</param>
''' <param name="sKey">String -> Name of the SubKey you want to delete a value from</param>
''' <param name="sKeyName">String -> Name of the value to delete</param>
''' <returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function DeleteSubKeyValue(ByVal MainKey As RegistryKey, ByVal sKey As String, ByVal sKeyName As String) As Boolean
Dim rkKey As RegistryKey
Try
'open the given subkey
rkKey = MainKey.OpenSubKey(sKey, True)
'check to make sure the subkey exists
If Not sKey Is Nothing Then 'subkey exists
'delete the subkey
MainKey.DeleteValue(sKeyName, True)
Return True
Else 'subkey doesnt exist
'throw an exception
Throw New Exception("The SubKey provided doesnt exist! Please check your entry and try again")
Return False
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: Deleting SubKey Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
End Function
The next function deletes the Sub Key itself. Remember, when you delete a Sub Key all the Value Entries it contained are deleted as well.
CODE
''' <summary>
''' Function to delete a SubKey from the Windows Registry
''' </summary>
''' <param name="MainKey">RegistryKey -> One of the top main keys to delete from</param>
''' <param name="sKey">String -> Name of the SubKey to delete</param>
''' <returns>True (Succeeded)/False (Failed)</returns>
''' <remarks>Created 23JUN05 -> Richard L. McCutchen</remarks>
Public Function DeleteRegistrySubKey(ByVal MainKey As RegistryKey, ByVal sKey As String) As Boolean
Dim rkKey As RegistryKey
Try
'open the given subkey
rkKey = MainKey.OpenSubKey(sKey, True)
'check to make sure the subkey exists
If Not sKey Is Nothing Then 'subkey exists
MainKey.DeleteSubKey(sKey, True)
Return True
Else 'subkey doesnt exist
'throw an exception letting the user know
Throw New Exception("The SubKey provided doesn't exist. Please check your entry and try again.")
Return False
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: Deleting SubKey", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
End Function
There you have it, a wrapper class for working with the Windows Registry. It is much easier than expected in .Net, I can remember working with the Windows Registry in VB6 and it was, to say the least, a nightmare. .Net made a programmers life some much easier.
I am providing both the source code and the DLL for this wrapper class, it is under a GNU General Public License so I request you leave the License Header in place. With the GNU General Public License you are free to modify this code, all I ask is if you use this wrapper in production is a reference to the author (me)