我想从注册表中检索值。例如:HKEY_LOCAL_MACHINE\SOFTWARE\Manufacturer's name\Application name\InstallInfo
在“InstallInfo”下有很多变量,比如 ProductVersion、WebsiteDescription、WebSiteDirectory、CustomerName、WebSitePort 等
我想检索这些变量的一些值。我尝试了以下代码,但它返回了
'Object reference not set to an instance of an object'
var regKey = Registry.LocalMachine;
regKey = regKey.OpenSubKey(@"SOFTWARE\ABC Limited\ABC Application\InstallInfo");
if (regKey == null)
{
Console.WriteLine("Registry value not found !");
}
else
{
string dirInfo = (string)regKey.GetValue("WebSiteDirectory");
Console.Write("WebSiteDirectory: " + dirInfo);
}
Console.ReadKey();
最佳答案
OpenSubKey
returns null
when it fails .这显然是这里发生的事情。
失败是因为您在错误的根键下查找。您正在 HKCU 下查找,但 key 在 HKLM 下。
所以你需要
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Manufacturer's name\Application name\InstallInfo");
当您调用 OpenSubKey
时,您必须始终检查返回值。如果它是 null
,则处理该错误情况。
if (regKey == null)
// handle error, raise exception etc.
另一件需要注意的事情是 registry redirector .如果您的进程是在 64 位系统上运行的 32 位进程,那么您将看到注册表的 32 位 View 。这意味着您尝试查看 HKLM\Softare
会透明地重定向到 HKLM\Software\Wow6432Node
。
关于c# - 如何从注册表中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16417989/