Check if a key exists in the Windows registry with VB.NET

In VB.NET, I can create a key in the Windows registry, for example:

My.Computer.Registry.CurrentUser.CreateSubKey("TestKey")

And I can check if a value exists inside such a key:

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

But how can I check if a key exists in the registry with a specific name?

+5
source share
1 answer

One way is to use the method Registry.OpenSubKey

If Microsoft.Win32.Registry.LocalMachine.OpenSubKey("TestKey") Is Nothing Then
  ' Key doesn't exist
Else
  ' Key existed
End If

However, I would advise you not to follow this path. The return Nothingmethod OpenSubKeymeans that the key did not exist at some point in the past. By the time the method returns another operation in another program, it may have triggered a key creation.

, , CreateSubKey.

+6

All Articles