从包含空格的 REG_SZ 类型读取注册表数据值

问题描述 投票:0回答:1

我一直在用头撞墙,我碰巧从另一个解决方案中获取了这段代码

所以基本上我需要读取注册表,检查其中的值是否与应用程序上的预设值匹配,并报告是或否。

它不是一个整数,而是一串字母和数字,但键的名称有空格,会抛出异常。

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

我在

Dim nValue As String = sk.GetValue("Application Name")

抛出异常

例如,当值是数字且键上没有空格时,原始代码效果很好;

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

基本上,我需要上面的代码来处理第一个示例,其中值数据不是数字并且值名称上有空格。

旁注,尝试的另一个解决方案是以下代码:

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

它在

Dim ST As String = rk2.GetValue("Application Name")

抛出相同的异常

我正在 64b 下编译,该项目选择了 x64 作为处理器。

vb.net registry
1个回答
0
投票

我最终用来避免对象引用错误触发的代码是:

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

结束使用

非常感谢您的提示和支持@jmcilhinney

© www.soinside.com 2019 - 2024. All rights reserved.