Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Because you can use the GetSetting and SaveSetting functions to access keys only under HKEY_CURRENT_USER\Software\VB and VBA Program Settings, you may find them limiting. When that happens, you can use the Registry and RegistryKey classes in the Microsoft.Win32 namespace of the .NET Framework. For more information, see Registry Class and RegistryKey Class.
Security Note It is more secure to write data to the current user (Microsoft.Win32.Registry.CurrentUser) than to the local computer (Microsoft.Win32.Registry.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 the RegistryKey.GetValue method. It returns Nothing if the key does not already exist.
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.
|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 machine.|
|PerformanceData||Contains performance information for software components.|
|Users||Contains information about the default user preferences.|
The following example shows how to read a DWORD value from HKEY_CURRENT_USER:
Imports Microsoft.Win32 Dim regVersion As RegistryKey Dim keyValue As String keyValue = "Software\\Microsoft\\TestApp\\1.0" regVersion = Registry.CurrentUser.OpenSubKey(keyValue, False) Dim intVersion As Integer = 0 If (Not regVersion Is Nothing) Then intVersion = regVersion.GetValue("Version", 0) regVersion.Close() End If
The following example reads, increments, and then writes a DWORD value to HKEY_CURRENT_USER:
Imports Microsoft.Win32 Dim regVersion As RegistryKey regVersion = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", True) If regVersion Is Nothing Then ' Key doesn't exist; create it. regVersion = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0") End If Dim intVersion As Integer = 0 If (Not regVersion Is Nothing) Then intVersion = regVersion.GetValue("Version", 0) intVersion = intVersion + 1 regVersion.SetValue("Version", intVersion) regVersion.Close() End If