[英]How to read Windows Server 2008 in c#
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 当我在Windows XP中尝试时,它工作正常,但我从未在Windows Server 2008中工作。任何帮助,请
You are probably running into the issue of the WOW redirector . 您可能正在遇到WOW重定向器的问题。
You can use the more specialized classes in Microsoft.Win32 for getting either a 64 or 32 bits part of the hive. 您可以在Microsoft.Win32中使用更专业的类来获取配置单元的64位或32位。
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: 如果我使用此注册表文件,则此代码适用于32位配置单元:
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: 这适用于64位配置单元:
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
来验证您的注册表路径是否存在:
reg query HKLM\Software\MyWeb\ConnectionManager /s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.