Question

In VB.NET I can create a key in the Windows Registry like this:

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

And I can check if a value exists within a key like this:

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 with a specific name exists in the Registry?

Was it helpful?

Solution

One way is to use the Registry.OpenSubKey method

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

However I would advise that you do not take this path. The OpenSubKey method returning Nothing means that the key didn't exist at some point in the past. By the time the method returns another operation in another program may have caused the key to be created.

Instead of checking for the key existence and creating it after the fact, I would go straight to CreateSubKey.

OTHER TIPS

I use this code. It’s simple, easy, and it works on HKEY_CURRENT_USER\Software\YourAppSettings.

Code:

string[]  kyes=Registry.CurrentUser.OpenSubKey(@"Software\YourAppSettings").GetValueNames();
if (!kyes.Contains("keytoknowIfExist"))
      {

      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top