Accessing the Registry with Visual Basic .NET
Visual Studio Team
Summary: This article describes how to access the registry using the Visual Basic .NET built-in functions, DeleteSetting, GetAllSettings, GetSetting and SaveSetting, as well as using the Registry and RegistryKey classes of the common language runtime. It details the required permissions, explains when to use the Registry Editor, and shows you how to read from and write to the registry programmatically. (5 printed pages)
Accessing the Registry with Visual Basic .NET Functions
Accessing the Registry with the .NET Framework
Accessing the Registry with the Registry Editor
When programming in Visual Basic® .NET, you can choose to access the registry via either the functions provided by Visual Basic .NET or the registry classes of the .NET Framework. While the Visual Basic functions prove sufficient in most cases, some situations may require using the .NET Framework.
The registry hosts information from the operating system as well as information from applications hosted on the machine. Working with the registry may compromise security. Therefore, you must closely scrutinize code that accesses the registry to ensure that it poses no threat to the security of the machine on which it will run.
Registry entries contain two parts: the value name and the value. Entries are stored under keys and subkeys in a system that is analogous to the file system, where files are stored in directories and subdirectories.
Getting the most out of this article has the following prerequisites:
- Familiarity with previous versions of Visual Basic.
- Knowledge of the design and purpose of the registry
- Understanding of the security implications of accessing the registry.
Visual Basic .NET offers four functions to access the registry. To use them, you must have Read and Write permission from the RegistryPermissionAccess enumeration. Any code running with full trust (under the default security policy, this is any code installed on the user's local hard drive) has the necessary permissions to access the registry. For more information, see RegistryPermission Class.
|Visual Basic .NET Function||Description|
|DeleteSetting||Deletes a section or key setting from an application's entry in the registry.|
|GetSetting||Returns a key setting value from an application's entry in the registry.|
|GetAllSettings||Returns a list of key settings and their values from an application's entry in the registry.|
|SaveSetting||Creates or saves an application entry in the registry.|
Note Section names cannot be returned via the GetSetting function.
If the key setting cannot be saved, an ArgumentException object is thrown. For more information on this exception, see ArgumentException.
The following example creates a registry key and two subkeys. It prints the first key's value and then prints the values of the first key as well as its subkeys. It then deletes the second subkey and prints the values of the first key and its subkeys to confirm the deletion of the second subkey.
' Create the first key. SaveSetting("TestApp","Startup","FirstKey","First") ' Create the first subkey. SaveSetting("TestApp","FirstKey","FirstSubKey","FirstSub") ' Create the second subkey. SaveSetting("TestApp","FirstKey","SecondSubKey","SecondSub") Try ' Write the first key's value. Console.WriteLine ((GetSetting("TestApp","Startup","FirstKey")) ' Write the first key as well as its two subkeys. Console.WriteLine (GetAllSettings("TestApp","Startup")) Catch e As ArgumentException Catch e As Exception Console.WriteLine (e.GetType.ToString) Finally End Try DeleteSetting("TestApp","FirstKey","SecondSubKey") Try Console.WriteLine (GetSetting("TestApp","Startup","FirstKey")) Console.WriteLine (GetAllSettings("TestApp","Startup")) Catch e As ArgumentException Catch e As Exception Console.WriteLine (e.GetType.ToString) Finally End Try
There is a limitation to using the built-in registry access functions: You can access only the registry keys under HKEY_CURRENT_USER\Software\VB and VBA Program Settings. To do so, you must be logged onto the system because the HKEY_CURRENT_USER registry key is not active until you log on to the system.
Registry settings that are to be accessed from a noninteractive process (such as mtx.exe) should be stored under either the HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
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 and RegistryKey
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
The RegistryPermission class, which is in the System.Security.Permission namespace, controls the ability to access registry variables. Registry variables should not be stored in memory locations where code without RegistryPermission can access them. Similarly, when granting permissions, grant the least privilege necessary to get the job done. For more information, see RegistryPermission and System.Security.Permissions.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. For more information, see RegistryPermissionAccess. The following table details its members.
|AllAccess||Create, read, and write access to registry variables.|
|Create||Create access to registry variables.|
|NoAccess||No access to registry variables.|
|Read||Read access to registry variables.|
|Write||Write access to registry variables.|
Note If you need some combination of permissions, such as permitting read and write access while denying create access, you can combine them with a bitwise Or operation, as in this example:
RegistryPermissionAccess.Write Or RegistryPermissionAccess.Read _
When working with deployment projects, you also have the option of using the Registry Editor to specify registry keys and values to be added to the registry of the target computer. For more information, see Registry Editor.
To access the Registry Editor
- Open a deployment project.
- On the View menu, point to Editor, and then click Registry.
For more information on using the Registry Editor in deployment projects, see Registry Settings Management in Deployment.
The registry is an optimal location for saving information about your application as well as individual user settings. You may also need to check information about system hardware, or applications with which yours will interact.
For most projects, accessing the registry via Visual Basic runtime functions is sufficient. On occasion, however, you may need to use the Registry and RegistryKey classes of the .NET Framework. In either case, it is a relatively simple task, but because such access has security implications, you should be careful not to create a security gap, such as including a plain text password or other sensitive information in a key.