Skip to main content
 首页 » 编程设计

c#之无法从现有键中读取值

2024年02月13日14EasonJim

我无法从注册键中读取值.. 出于某种奇怪的原因。路径是正确的..并且 key 存在。我不知道为什么它无法读取它。

我有一些代码(读取注册表)

string local  = Microsoft.Win32.Registry.LocalMachine.ToString(); 
        string javaRegPath = "\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\"; 
        if (javaRegPath != null) 
        { 
            string javaVersion = Registry.readReg(local + javaRegPath, "CurrentVersion").ToString(); 
            string javaHome = Registry.readReg(javaRegPath + "\\" + javaVersion, "JavaHome").ToString(); 
            return javaHome; 
        } 

Registry.cs(阅读)

public static object readReg(string keyPath, string keyName) 
    { 
        key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyPath); 
        return  key.GetValue(keyName); 
    } 

这是一张来自注册表编辑器的图片。验证路径等。 registry http://bumisworld.eu/reg.png

但它只返回一个 NPE...

留言: The Bukkit GUI Project.exe 中发生类型为“System.NullReferenceException”的未处理异常

附加信息:未将对象引用设置为对象的实例。

registry http://bumisworld.eu/locals2.png

有什么帮助吗?

请您参考如下方法:

我能看到几个问题。

首先,readReg 实际上是在 Registry.CurrentUser 上调用 OpenSubKey。从 HKCU 读取。您需要为 HKLM 使用 Registry.LocalMachine。将根 key 作为额外参数传递给 readReg。

最重要的是,您可能会被 registry redirector 捕获.您的 32 位进程(好吧,我假设您的进程是 32 位的)被重定向到注册表的 32 位 View 。但您要查找的 key 位于注册表的 64 位 View 中。

换句话说,您尝试访问 HKLM\Software 被重定向到 HKLM\Software\Wow6432Node。

使用 RegistryView枚举以允许您的 32 位进程访问注册表的 64 位 View 。


还应修改您的 readReg 函数以检查对 OpenSubKey 的调用中的错误。该方法可以返回 null。您应该以更简洁的方式处理该场景,然后抛出 NullReferenceException。