Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft.Win32.Registry's GetValue Doesn't Use Default Value

I have a legacy (I didn't build it) application running on an x64 environment (Win7). I have a sneaking suspicion it was run on a 32-bit environment before.

Anyway, I see calls to Registry.GetValue(key, value, default).

It seems like the default value is ignored.

Check out this crazy code:

// Up above the sky, so high
using Microsoft.Win32;
// ...
string location = "HKEY_LOCAL_MACHINE\SOFTWARE\..."; // ...
// ...

string registryValue = (string)Registry.GetValue(location, "Uri", "http://localhost/");
if (string.isNullOrEmpty(registryValue) {
  throw new Exception("What the ... ?!");
}

In a comparable example, the exception is seriously being thrown. (Actually, a null-reference exception appears despite the default value).

And I checked that I have the registry keys all the way up to the last level; they're all in my registry.

This works for someone, but not for me.

Is this a bug? What's going on here?

like image 917
ashes999 Avatar asked Jul 20 '26 08:07

ashes999


1 Answers

Most likely you are being caught out by registry redirection. You have a 32 bit process running on a 64 bit system. So HKLM\Software is redirected to HKLM\Software\Wow6432Node.

When the key does not exist, the Registry.GetValue returns null rather than the default value and so the exception is thrown.

If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.

like image 123
David Heffernan Avatar answered Jul 21 '26 23:07

David Heffernan