创建注册表时出错

时间:2013-06-03 01:02:16

标签: vb.net vb.net-2010

我的vb.net程序创建/打开/编辑注册表文件。开发之后,当我将程序用于另一台计算机时,它会返回错误:

Error

如果我将注册表文件导入计算机,程序运行正常,所以我猜错误与创建注册表文件有关。

这是程序创建注册表文件的方式:

Function createRegistrykey()
    Dim openKey As RegistryKey
    openKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\RobinsonsRetailGroup\LogSettings", True)

    '[SPECIFICATION]
    If (openKey.GetValue("STORENAME") = Nothing) Then
        openKey.SetValue("STORENAME", "RRR", RegistryValueKind.String)
    End If
    If (openKey.GetValue("STORENUMBER") = Nothing) Then
        openKey.SetValue("STORENUMBER", "000", RegistryValueKind.String)
    End If

    '[DEFAULT]
    If (openKey.GetValue("UTILFLR") = Nothing) Then
        openKey.SetValue("UTILFLR", "C:\Util", RegistryValueKind.String)
    End If
    If (openKey.GetValue("GRSFLR") = Nothing) Then
        openKey.SetValue("GRSFLR", "D:\DC\Instances\", RegistryValueKind.String)
    End If
    If (openKey.GetValue("EXPORTFLR") = Nothing) Then
        openKey.SetValue("EXPORTFLR", "C:\Export", RegistryValueKind.String)
    End If
    If (openKey.GetValue("OFFICEIMPFLR") = Nothing) Then
        openKey.SetValue("OFFICEIMPFLR", "C:\Program Files\", RegistryValueKind.String)
    End If
    If (openKey.GetValue("PCMSTBAKFLR") = Nothing) Then
        openKey.SetValue("PCMSTBAKFLR", "C:\BAK", RegistryValueKind.String)
    End If
    If (openKey.GetValue("DBASEBAKFLR") = Nothing) Then
        openKey.SetValue("DBASEBAKFLR", "D:\Backup\Store", RegistryValueKind.String)
    End If
    If (openKey.GetValue("INTBACKUPFLR") = Nothing) Then
        openKey.SetValue("INTBACKUPFLR", "D:\BACKUP", RegistryValueKind.String)
    End If
    If (openKey.GetValue("EXTBACKUPFLR") = Nothing) Then
        openKey.SetValue("EXTBACKUPFLR", "none", RegistryValueKind.String)
    End If

    '[POS]
    If (openKey.GetValue("POSUSER") = Nothing) Then
        openKey.SetValue("POSUSER", "Administrator", RegistryValueKind.String)
    End If
    If (openKey.GetValue("POSPASS") = Nothing) Then
        openKey.SetValue("POSPASS", hashEncoding("isd"), RegistryValueKind.String)
    End If

    If (openKey.GetValue("LOGVIEWERPASS") = Nothing) Then
        openKey.SetValue("LOGVIEWERPASS", hashEncoding("BBOEY"), RegistryValueKind.String)
    End If

    openKey.Close()
    Return vbNull
End Function

有人知道为什么会出现这个错误吗?

1 个答案:

答案 0 :(得分:1)

来自MSDN,关于RegistryKey.OpenSubKey方法:

  

如果请求的密钥不存在,则此方法返回null而不是抛出异常。

您在不存在密钥的工作站上拥有的Null reference exception(在{null} registryKey对象的第一次调用GetValue时发生)完全正常。

'[SPECIFICATION]
    If (openKey.GetValue("S...

因此,在使用密钥执行任何操作之前,您应该测试它是否为空。

Dim openKey As RegistryKey
    openKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\RobinsonsRetailGroup\LogSettings", True)

If openKey IsNot Nothing
 (...)
Else
 (...)
End if

如果您想要创建密钥(如果密钥不存在),则应使用将创建密钥的RegistryKey.CreateSubKey方法,或者如果已存在则将其打开以进行写访问。

Dim openKey As RegistryKey
    openKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\RobinsonsRetailGroup\LogSettings")

希望这有帮助。