Share via


How to: Set Values in Registry Keys in Visual Basic

The SetValue method of the My.Computer.Registry object can be used to write values in the Windows registry. 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 value, including the complete key path, is created if it does not exist.

Procedure

To write a value to a registry key

  • Use the SetValue method, specifying the key and value. This example sets the value Name to "Author's Name" in the key HKEY_CURRENT_USER\Software\TestApp.

    My.Computer.Registry.SetValue _
        ("HKEY_CURRENT_USER\Software\TestApp", "Name", "Author's Name")
    

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 How to: Insert Snippets Into Your Code (Visual Basic).

Robust Programming

User preference data should be written to the Microsoft.Win32.Registry.CurrentUser hive.

It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by access control lists (ACLs).

The following conditions may cause an exception:

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.

See Also

Tasks

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

Troubleshooting: Manipulating the Registry

Concepts

Common Registry Tasks

Reference

My.Computer.Registry Object Members

My.Computer.Registry.SetValue Method

Other Resources

Walkthrough: Creating a Registry Key and Changing Its Values