使用VB.NET检查Windows注册表中是否存在密钥

Max*_*Max 5 vb.net windows registry key-value registrykey

在VB.NET中,我可以在Windows注册表中创建一个键,如下所示:

My.Computer.Registry.CurrentUser.CreateSubKey("TestKey")
Run Code Online (Sandbox Code Playgroud)

我可以检查一个键中是否存在这样的:

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
Run Code Online (Sandbox Code Playgroud)

但是,如何检查注册表中是否存在具有特定名称的密钥

Jar*_*Par 6

一种方法是使用该Registry.OpenSubKey方法

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

但是我会建议你不要走这条路.该OpenSubKey方法返回Nothing的关键并不在过去的某个时间存在的手段.当方法返回另一个程序中的另一个操作时,可能导致创建密钥.

我不会检查密钥存在并在事后创建密钥,而是直接进行CreateSubKey.