Search code examples
vb.netregistry

Read registry data value from a REG_SZ type that contains a space


I've been banging my head on the wall on this, I happened to fetch this code from another solution

So basically I need to read the registry, check if the value in it matches a pre-set value on the application and report yes or no.

It is not an integer, it's a string of letters and numbers, but the name of the key has a space and it throws an exception.

Using sk As RegistryKey = rkLocalMachine.OpenSubKey("SOFTWARE\WOW6432Node\X\41821-SAP-GUIPL8HF1-7700.1.8.1162-EN-GBL-R3", False)
Dim nValue As String = sk.GetValue("Application Name")
If nValue = "GUIPL8HF1" Then
Timer2.Stop()
End If
End Using

I get the exception thrown at Dim nValue As String = sk.GetValue("Application Name")

the original code works well for when the values are numbers and no spaces on the keys, for example;

Using sk As RegistryKey = rkLocalMachine.OpenSubKey("SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services", False)
Dim nValue As Integer = CType(sk.GetValue("fDenyTSConnections"), Integer)
If nValue = "1" Then
RDPstatus.ForeColor = Color.Red
Else
RDPstatus.ForeColor = Color.Chartreuse
End If
End Using

basically, I need the above code to work for the first example where the value data is not a number and the value name has a space on it.

On a sidenote, another solution attempted was the following code:

Dim rk1 As RegistryKey
Dim rk2 As RegistryKey
rk1 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
rk2 = rk1.OpenSubKey("SOFTWARE\WOW6432Node\X\41821-SAP-GUIPL8HF1-7700.1.8.1162-EN-GBL-R3")
Dim ST As String = rk2.GetValue("Application Name")
If ST = "GUIPL8HF1" Then
TIMER2.Stop()
End If

it throws the same exception at Dim ST As String = rk2.GetValue("Application Name")


I'm compiling at 64b, the project has x64 as processor selected.


Solution

  • The code I ended up using to avoid the object reference error trigger is:

    Using sk As RegistryKey = rkLocalMachine.OpenSubKey("SOFTWARE\WOW6432Node\X\41821-SAP-GUIPL8HF1-7700.1.8.1162-EN-GBL-R3", False)
        If sk IsNot Nothing Then
            Dim nValue As String = sk.GetValue("Application Name") 
            If nValue = "GUIPL8HF1" 
            Then
                sappatchstatus.ForeColor = Color.Chartreuse
                sapinstall.Enabled = False 
            Else
                sappatchstatus.ForeColor = Color.Red
                sapinstall.Enabled = True
            End If 
        Else 
            sappatchstatus.ForeColor = Color.Red
            sapinstall.Enabled = True 
        End If 
    End Using
    

    End Using

    Thank you very much for your hints and support @jmcilhinney