# Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace (Visual Basic)

Although My.Computer.Registry should cover your basic needs when programming against the registry, you can also use the Registry and RegistryKey classes in the Microsoft.Win32 namespace of .NET.

## Keys in the Registry Class

The Registry class supplies the base registry keys that can be used to access subkeys and their values. The base keys themselves are read-only. The following table lists and describes the seven keys exposed by the Registry class.

Key Description
ClassesRoot Defines the types of documents and the properties associated with those types.
CurrentConfig Contains hardware configuration information that is not user-specific.
CurrentUser Contains information about the current user preferences, such as environmental variables.
DynData Contains dynamic registry data, such as that used by Virtual Device Drivers.
LocalMachine Contains five subkeys (Hardware, SAM, Security, Software, and System) that hold the configuration data for the local computer.
PerformanceData Contains performance information for software components.
Users Contains information about the default user preferences.

Important

It is more secure to write data to the current user (CurrentUser) than to the local computer (LocalMachine). A condition that's typically referred to as "squatting" occurs when the key you are creating was previously created by another, possibly malicious, process. To prevent this from occurring, use a method, such as GetValue, that returns Nothing if the key does not already exist.

## Reading a Value from the Registry

The following code shows how to read a string from HKEY_CURRENT_USER.

Dim regVersion As Microsoft.Win32.RegistryKey
Dim keyValue = "Software\\Microsoft\\TestApp\\1.0"
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyValue, False)
Dim intVersion As Integer = 0
If regVersion IsNot Nothing Then
intVersion = regVersion.GetValue("Version", 0)
regVersion.Close()
End If


The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.

Dim regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
' Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
"SOFTWARE\\Microsoft\\TestApp\\1.0")
End If

Dim intVersion As Integer = 0
If regVersion IsNot Nothing Then
intVersion = regVersion.GetValue("Version", 0)
intVersion = intVersion + 1
regVersion.SetValue("Version", intVersion)
regVersion.Close()
End If