Check if a key exists in the Windows Registry with VB.NET
Asked Answered
H

3

7

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?

Hexane answered 1/4, 2013 at 14:51 Comment(0)
L
8

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.

Lasagne answered 1/4, 2013 at 14:56 Comment(1)
THIS MAY NOT ALWAYS WORK. A 32-bit application on a 64-bit OS will be looking at the HKLM\Software\Wow6432Node node by default. To read the 64-bit version of the key, you'll need to specify the RegistryViewDugald
P
0

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"))
      {

      }
Ploss answered 26/11, 2020 at 18:59 Comment(0)
R
0

Thanks for the information - this helped me a lot! I did notice while I am in the Visual Studio development module however, the settings were being saved under Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Elementary\Backup - not the same as the finished Installed Software. I am using ie. SaveSetting("Elementary", "Backup", "BackupFile", bdbname)

Since I didn't know exactly where my settings would be saved in the registry once my product was completed, I tried this and it worked perfect for me. I didn't have to know the exact location, which was helpful.

    If GetSetting("Elementary", "Backup", "BackupFile", Nothing) <> Nothing Then
        DeleteSetting("Elementary", "Backup", "BackupFile")
        bdbname = ""
    End If

Anyway, hope it helps someone in the future...

Rubberneck answered 24/4, 2022 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.