|
-
Dec 18th, 2002, 04:07 PM
#1
Thread Starter
New Member
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
-
Dec 18th, 2002, 05:08 PM
#2
Sleep mode
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:
Dim regkey as string
regKey =(getsetting("TestApp","Startup","key"))
it seems very simple ,isn't it!
-
Dec 19th, 2002, 10:13 AM
#3
Thread Starter
New Member
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
-
Dec 19th, 2002, 11:59 AM
#4
Fanatic Member
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.
-
Dec 19th, 2002, 12:39 PM
#5
Thread Starter
New Member
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:
Public Shared Function TestForKeyValue(ByVal Reg_Key_Path As String, _
ByVal KeyToFind As String) As String
Dim arrKeyNames() As String
Dim i As Int32
Dim reg_key As RegistryKey
Try
'open the key if it exists
reg_key = Registry.LocalMachine.OpenSubKey(Reg_Key_Path)
'get all the keynames for the requested heirarchy OR
'blow-out time!!
arrKeyNames = reg_key.GetValueNames()
'loop and match values
For i = 0 To UBound(arrKeyNames)
If KeyToFind = arrKeyNames(i) Then
Return reg_key.GetValue(KeyToFind)
End If
Next
Return Nothing
Catch nre As NullReferenceException
'capture the exception and use it to tell client app
'that there is no key w/ this name
Return Nothing
Catch e As Exception
Throw New Exception("The following error occured while testing the Registry Key", e)
Return Nothing
End Try
-
Dec 19th, 2002, 02:09 PM
#6
Fanatic Member
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.
-
Jan 16th, 2003, 11:32 AM
#7
Thread Starter
New Member
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:
Public Function TestForKeyValue(ByVal Reg_Key_Path As String, _
ByVal ValueToFind As String) As String
'****************************************************************************************************
'FUNCTION: tests if a value within a registry key exists
'Last Modified:
'****************************************************************************************************
Dim arrValueNames() As String
Dim iIndex As Int32
Dim reg_key As RegistryKey
Try
'open the key if it exists
reg_key = Registry.LocalMachine
If DoesKeyExist(Reg_Key_Path, reg_key) Then
'get all the values for the requested Key into array
arrValueNames = reg_key.GetValueNames()
'see if values is found in key
If Not arrValueNames Is Nothing Then
iIndex = Array.IndexOf(arrValueNames, ValueToFind)
If iIndex <> -1 Then 'IndexOf returns -1 when target is not found
Return reg_key.GetValue(ValueToFind)
End If
End If
Else
Return Nothing
End If
Catch nre As NullReferenceException
'capture the exception and use it to tell client app
'that there is no key w/ this name
Return Nothing
Catch e As Exception
Throw New Exception("The following error occured while testing the Registry Value", e)
Return Nothing
End Try
End Function
Private Function DoesKeyExist(ByVal Reg_Key_Path As String, _
ByRef Reg_Key As RegistryKey) As Boolean
'****************************************************************************************************
'FUNCTION: tests if a registry key exists
'Last Modified:
'****************************************************************************************************
Dim i, y As Int32
Dim bKey_Found As Boolean
Dim arrKeys_at_this_level(), arrPath() As String
Try
'break the path into components
arrPath = Reg_Key_Path.Split("\")
'drill down through path
For i = 0 To UBound(arrPath)
'get keys at the current level of the registry
arrKeys_at_this_level = Reg_Key.GetSubKeyNames
'reset flag
bKey_Found = False
For y = 0 To UBound(arrKeys_at_this_level) 'loop through this level
'if the
If arrKeys_at_this_level(y).ToUpper = arrPath(i).ToUpper Then
bKey_Found = True
Exit For
End If
Next
If bKey_Found Then
'if key is found then open it
Reg_Key = Reg_Key.OpenSubKey(arrPath(i))
Else
'some part of the path is broken ...
Return False
End If
Next
Return True
Catch nre As NullReferenceException
'capture the exception and use it to tell client app
'that there is no key w/ this name
Return False
Catch e As Exception
Throw New Exception("The following error occured while testing the Registry Key", e)
End Try
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|