Question

i am trying o read registry value with the following code.

    Label1.Text = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Myweb\\ConnectionManager", "ID", null).ToString();

it work fine when i am trying in windows xp but i never works in windows server 2008. any help Please

Was it helpful?

Solution

You are probably running into the issue of the WOW redirector.

You can use the more specialized classes in Microsoft.Win32 for getting either a 64 or 32 bits part of the hive.

 var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine
                                   ,RegistryView.Registry32); // or Registry64
 var flk = root.OpenSubKey("SOFTWARE");
 var slk = flk.OpenSubKey("Myweb");
 var tlk = slk.OpenSubKey("ConnectionManager");
 var val = tlk.GetValue("ID");

 Label1.Text = val.ToString();

Or a more general purpose method to get a registry value whatever it takes:

object GetValue64Or32(string path, string ValueKey)
{
     var parts = path.Split('\\');
     RegistryHive hive = RegistryHive.LocalMachine;
     switch(parts[0])
     {
        case "HKEY_LOCAL_MACHINE":
            hive = RegistryHive.LocalMachine;
        break;
        default:
           throw new NotImplementedException();
     }
     foreach(var view in Enum.GetValues(typeof(RegistryView)))
     {
        var key = RegistryKey.OpenBaseKey(hive, (RegistryView) view);
        for(var partIndex=1; partIndex<parts.Length;partIndex++)
        {
           key = key.OpenSubKey(parts[partIndex]);
           if (key == null) break;
        }
        if (key!=null) return key.GetValue(ValueKey);
     }
     return null;
}

Usage:

var value = GetValue64Or32(
               "HKEY_LOCAL_MACHINE\\SOFTWARE\\Myweb\\ConnectionManager"
             , "ID");
Label1.Text = value!=null?value.ToString():"no value found";

If I use this registry file this code works for the 32 bits hive:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyWeb\]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyWeb\ConnectionManager\]
"ID"="id 1"

And this works for the 64 bits hive:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\MyWeb\]

[HKEY_LOCAL_MACHINE\SOFTWARE\MyWeb\ConnectionManager\]
"ID"="id 1"

You can use REG from the commandprompt to verify if your registrypath exists:

reg query HKLM\Software\MyWeb\ConnectionManager /s
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top