How to: Read a Value from a Registry Key in Visual Basic

The GetValue method of the My.Computer.Registry object can be used to read values in the Windows registry.

If the key, "Software\MyApp" in the following example, does not exist, an exception is thrown. If the ValueName, "Name" in the following example, does not exist, Nothing is returned.

The GetValue method can also be used to determine whether a given value exists in a specific registry key.

When code reads the registry from a Web application, the current user is determined by the authentication and impersonation that is implemented in the Web application.

To read a value from a registry key

  • Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.

    Dim readValue = My.Computer.Registry.GetValue(
        "HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
    MsgBox("The value is " & readValue)
    

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Operating System > Registry. For more information, see Code Snippets.

To determine whether a value exists in a registry key

  • Use the GetValue method to retrieve the value. The following code checks whether the value exists and returns a message if it does not.

    If My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\TestApp",
    "TestValue", Nothing) Is Nothing Then
        MsgBox("Value does not exist.")
    End If
    

Robust Programming

The registry holds top-level, or root, keys that are used to store data. For instance, the HKEY_LOCAL_MACHINE root key is used for storing machine-level settings used by all users, while HKEY_CURRENT_USER is used for storing data specific to an individual user.

The following conditions may cause an exception:

.NET Framework Security

To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission might not have operating system permission. For more information, see Code Access Security Basics.

Note

Code Access Security (CAS) has been deprecated across all versions of .NET Framework and .NET. Recent versions of .NET do not honor CAS annotations and produce errors if CAS-related APIs are used. Developers should seek alternative means of accomplishing security tasks.

See also