سؤال

I can't read a value from a reg key.. For some weird reason. The path is correct.. And the key exist. I have no idea why it can't read it.

Bit of code that I have(that read the registry)

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 (read)

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

And here is an image from Registry Editor. To verify the paths and so on. registry http://bumisworld.eu/reg.png

But it just returns a NPE...

Message: An unhandled exception of type 'System.NullReferenceException' occurred in The Bukkit GUI Project.exe

Additional information: Object reference not set to an instance of an object.

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

Any help on this?

هل كانت مفيدة؟

المحلول

A couple of problems that I can see.

Firstly readReg is actually calling OpenSubKey on Registry.CurrentUser. That reads from HKCU. You need to use from Registry.LocalMachine for HKLM. Pass the root key to readReg as an extra parameter.

On top of that you will likely be caught out by the registry redirector. Your 32 bit process (well, I assume your process is 32 bit) is redirected to the 32 bit view of the registry. But the key you are looking for is in the 64 bit view of the registry.

In other words your attempt to access HKLM\Software is being redirected to HKLM\Software\Wow6432Node.

Use the RegistryView enumeration to allow your 32 bit process to access the 64 bit view of the registry.


Your readReg function should also be modified to check for errors in the call to OpenSubKey. That method can return null. You should deal with that scenario in a cleaner way then let a NullReferenceException be thrown.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top