Search code examples
vb.netregistry

How do I check to see if a registry entry exists?


I'm trying to see if a registry key exists. If it does, I do on thing, if not, I do something else. I've tried different things, but so far none have worked.

I've tried:

If My.Computer.Registry.CurrentUser.GetValue("MySubKey", True) Is Nothing Then

Also, I've tried to see if regKey var is nothing. And a few others I can't remember.

Any ideas?

thanks


Solution

  • To check if a Registry key exists you can use this...

      'Obtain an instance of RegistryKey for the CurrentUser registry root. 
       Dim rkCurrentUser As RegistryKey = Registry.CurrentUser
      ' Obtain the key (read-only) and display it.
       If rkCurrentUser IsNot Nothing Then
          Dim rkTest As RegistryKey = rkCurrentUser.OpenSubKey("MySubKey")
    
          'Check and make sure we have something...
          If rkTest IsNot Nothing Then
             'You have something then...
    
             rkTest.Close 'Close it, this is important...
          Else
             'You do not have anything...
          End If 
    
          rkCurrentUser.Close 'Close this after you are done...
       Else
          'Failed to get instance of registry for the current user...
       End If
    

    There are other ways as well, but let me know how this works out for you...