Question not able to read registry

eagle00789

New member
Joined
Sep 14, 2014
Messages
2
Programming Experience
5-10
I have the following 2 lines of code to read some value from the registry upon opening my about-form, but the registry isn't being read and the default value isn't used.
VB.NET:
        Dim LicenseTo = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\sample\app\License", "LicenseTo", "DEMO")
        Dim LicenseKey = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\sample\app\License", "LicenseKey", "DEMO")
What am i doing wrong and why is the default value not being used...
 
You say that you're doing that upon opening the form so I'm guessing that that means in the Load event handler. On a 64-bit system, exceptions thrown in the Load event handler are swallowed and execution jumps out of the event handler and continues. I'd say that that's what's happening to you. Wrap that code in a Try...Catch block and see what the exception is.
 
Full sollution:
VB.NET:
        Dim regKey As RegistryKey
        Dim LicenseTo As String
        Dim LicenseKey As String
        regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\sample\app\License", False)
        If (regKey Is Nothing) Then
            LicenseTo = "DEMO"
            LicenseKey = "DEMO"
        Else
            LicenseTo = regKey.GetValue("LicenseTo", "DEMO")
            LicenseKey = regKey.GetValue("LicenseKey", "DEMO")
        End If
Because the key doesn't exist, the value of regKey is NOTHING, so you have to catch that small error before reading the registry
 
You don't need that "manual" RegistryKey handling here, previous code will do that for you, but if you do then you must remember to call Close or Dispose method when you are done with it.

Regarding code in your first post, if the key doesn't exist the function will return Nothing. If the key exist and the valueName (eg "LicenceTo") doesn't, then it will return the default value (eg "Demo"). Simplified you can cover both cases using If operator called with two arguments:
Dim LicenseTo = If(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\sample\app\License", "LicenseTo", "DEMO"), "DEMO")
 

Latest posts

Back
Top