Results 1 to 7 of 7

Thread: Test if registry key exists

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2002
    Location
    Ottawa
    Posts
    5

    Question Test if registry key exists

    Anyone know of a better way of testing to see if a reg key exists? Currently I am just catching the nullreferenceexception and using that ... but I would prefer a "exists" method or the like ...

    Anyway, here is what I am doing ...

    Imports Microsoft.Win32

    Public Class cRegistry

    Public Shared Function TestForKey(ByVal Reg_Key_Path As String, _
    ByVal Reg_Value As String) As Boolean
    Dim s As String
    Dim reg_key As RegistryKey
    Dim reg_hive As RegistryHive

    Try

    reg_key = Registry.LocalMachine.OpenSubKey(Reg_Key_Path)
    If reg_key.ValueCount = 0 Then
    Return False
    Else
    Return True
    End If
    Catch nre As NullReferenceException
    Return False
    Catch e As Exception
    Throw New Exception("The following error occured while testing the Registry Key", e)
    End Try


    End Function

    End Class

  2. #2
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    there are two ways to access the registry : using the vb.net built-in functions(deletesetting,getallsettings,getsetting,savesetting)
    as well as using the registry and registrykey classess of the CLR.
    Some of them require permissions.

    'this code uses vb.net built-in functions
    VB Code:
    1. Dim regkey as string
    2. regKey =(getsetting("TestApp","Startup","key"))
    it seems very simple ,isn't it!

  3. #3

    Thread Starter
    New Member
    Join Date
    Dec 2002
    Location
    Ottawa
    Posts
    5
    Thanks for the reply Pirate!

    deletesetting,getallsettings,getsetting,savesetting would work fine, except that they only store the reg values under "HKEY_USERS\VB and VBA Program Settings" and I have to use a different location. As for using the CLR, the code I have uses those classes now ... but I can't seem to figure out how to test if the Key exists without inadvetantly throwing a nullref err.

    for instance:

    reg_key = Registry.LocalMachine.OpenSubKey(Reg_Key_Path)
    'this will blow-out
    If reg_key.ValueCount = 0 then
    '...
    End If

  4. #4
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    Seems to me you would rather be using the RegistryKey class.

    ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfmicrosoftwin32registrykeyclasstopic.htm

    There's a method called GetSubKeyNames that looks like it will do what you want, if you feed it the full path to the key you want to examine:

    ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfmicrosoftwin32registrykeyclassgetsubkeynamestopic.htm

    Rather than try to open the subkey without knowing if it exists and rely on exception handling to test if the key is present, you might want to examine the array returned by GetSubKeyNames instead. Your way also looks like it works, but it relies on a value being present under the key. Hope this helps.

  5. #5

    Thread Starter
    New Member
    Join Date
    Dec 2002
    Location
    Ottawa
    Posts
    5
    Originally posted by Slow_Learner
    There's a method called GetSubKeyNames that looks like it will do what you want ...
    I guess I had my terminology mixed up! I actually wanted to test for Values within a key, not keys!! Ah ... clarity. That being said ... GetSubKeyNames was almost what I wanted. I used GetValueNames() ... which works identically, except it returns value names instead. This works perfectly IF the key exists regardless of whether or not there are values present. However, if the key DOESN'T exist ... you will still receive a null ref exception when you call the reg_key.GetValueNames!

    Here is what I tried:
    VB Code:
    1. Public Shared Function TestForKeyValue(ByVal Reg_Key_Path As String, _
    2.                                 ByVal KeyToFind As String) As String
    3.         Dim arrKeyNames() As String
    4.         Dim i As Int32
    5.         Dim reg_key As RegistryKey
    6.  
    7.         Try
    8.             'open the key if it exists
    9.             reg_key = Registry.LocalMachine.OpenSubKey(Reg_Key_Path)
    10.  
    11.             'get all the keynames for the requested heirarchy OR
    12.             'blow-out time!!
    13.             arrKeyNames = reg_key.GetValueNames()
    14.  
    15.             'loop and match values
    16.             For i = 0 To UBound(arrKeyNames)
    17.                 If KeyToFind = arrKeyNames(i) Then
    18.                     Return reg_key.GetValue(KeyToFind)
    19.                 End If
    20.             Next
    21.  
    22.             Return Nothing
    23.         Catch nre As NullReferenceException
    24.             'capture the exception and use it to tell client app
    25.             'that there is no key w/ this name
    26.             Return Nothing
    27.         Catch e As Exception
    28.             Throw New Exception("The following error occured while testing the Registry Key", e)
    29.             Return Nothing
    30.         End Try

  6. #6
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    518
    Then I'd suggest you first check to see if the key exists with GetSubKeyNames before calling GetValueNames for a particular key. Although if you're doing this onesy-twosy it won't matter much, I've found that for repetitive operations it is a Bad Thing to rely on exception handling wherever you can avoid it.

    By the way there's a slightly cleaner way to hunt through an array for a particular value:

    ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemarrayclassindexoftopic.htm

    Basically since you're just going to return a true/false value you may want to look at getting rid of the search loop you're testing the array with. You can just do something like:

    Code:
    Dim iIndex As Integer
    If Not arrKeyNames Is Nothing Then
        iIndex = IndexOf(arrKeyNames, KeyToFind)
        If iIndex <> -1 Then   'IndexOf returns -1 when target is not found
            Return reg_key.GetValue(KeyToFind)
        End If
    End If
    Again this doesn't matter if you're doing one check per buttonclick or something like that, but if you had to do a few hundred or more then you'd see a difference in speed, especially if you rely on the exception handler to do any kind of frequent activity. Glad you're getting somewhere.

  7. #7

    Thread Starter
    New Member
    Join Date
    Dec 2002
    Location
    Ottawa
    Posts
    5
    Finally got a chance to go back and take a look at this problem ... slow_learner thanks!

    Here is what I ended up with and I am pretty happy with it.

    VB Code:
    1. Public Function TestForKeyValue(ByVal Reg_Key_Path As String, _
    2.                                 ByVal ValueToFind As String) As String
    3.         '****************************************************************************************************
    4.         'FUNCTION:      tests if a value within a registry key exists
    5.         'Last Modified:
    6.         '****************************************************************************************************
    7.         Dim arrValueNames() As String
    8.         Dim iIndex As Int32
    9.         Dim reg_key As RegistryKey
    10.  
    11.         Try
    12.  
    13.             'open the key if it exists
    14.             reg_key = Registry.LocalMachine
    15.  
    16.             If DoesKeyExist(Reg_Key_Path, reg_key) Then
    17.                 'get all the values for the requested Key into array
    18.                 arrValueNames = reg_key.GetValueNames()
    19.  
    20.                 'see if values is found in key
    21.                 If Not arrValueNames Is Nothing Then
    22.                     iIndex = Array.IndexOf(arrValueNames, ValueToFind)
    23.                     If iIndex <> -1 Then   'IndexOf returns -1 when target is not found
    24.                         Return reg_key.GetValue(ValueToFind)
    25.                     End If
    26.                 End If
    27.             Else
    28.                 Return Nothing
    29.             End If
    30.         Catch nre As NullReferenceException
    31.             'capture the exception and use it to tell client app
    32.             'that there is no key w/ this name
    33.             Return Nothing
    34.         Catch e As Exception
    35.             Throw New Exception("The following error occured while testing the Registry Value", e)
    36.             Return Nothing
    37.         End Try
    38.  
    39.     End Function
    40.  
    41.     Private Function DoesKeyExist(ByVal Reg_Key_Path As String, _
    42.                                     ByRef Reg_Key As RegistryKey) As Boolean
    43.         '****************************************************************************************************
    44.         'FUNCTION:      tests if a registry key exists
    45.         'Last Modified:
    46.         '****************************************************************************************************
    47.  
    48.         Dim i, y As Int32
    49.         Dim bKey_Found As Boolean
    50.         Dim arrKeys_at_this_level(), arrPath() As String
    51.  
    52.         Try
    53.             'break the path into components
    54.             arrPath = Reg_Key_Path.Split("\")
    55.  
    56.             'drill down through path
    57.             For i = 0 To UBound(arrPath)
    58.                 'get keys at the current level of the registry
    59.                 arrKeys_at_this_level = Reg_Key.GetSubKeyNames
    60.  
    61.                 'reset flag
    62.                 bKey_Found = False
    63.                 For y = 0 To UBound(arrKeys_at_this_level) 'loop through this level
    64.                     'if the
    65.                     If arrKeys_at_this_level(y).ToUpper = arrPath(i).ToUpper Then
    66.                         bKey_Found = True
    67.                         Exit For
    68.                     End If
    69.                 Next
    70.  
    71.                 If bKey_Found Then
    72.                     'if key is found then open it
    73.                     Reg_Key = Reg_Key.OpenSubKey(arrPath(i))
    74.                 Else
    75.                     'some part of the path is broken ...
    76.                     Return False
    77.                 End If
    78.             Next
    79.             Return True
    80.         Catch nre As NullReferenceException
    81.             'capture the exception and use it to tell client app
    82.             'that there is no key w/ this name
    83.             Return False
    84.         Catch e As Exception
    85.             Throw New Exception("The following error occured while testing the Registry Key", e)
    86.         End Try
    87.     End Function

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width