简体   繁体   English

以字符串形式返回注册表值

[英]Returning a registry value as a string

I am trying to read another applications registry value but I am not having much success. 我正在尝试读取另一个应用程序注册表值,但是我没有太大的成功。 I have searched a full page and a half of results on Google, but not found what I am looking for. 我已经在Google上搜索了整整一页的结果,但没有找到我想要的东西。

I am trying to read the following registry value: 我正在尝试读取以下注册表值:

\\HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\AVG CloudCare\DisplayVersion

A typical value would be: '3.5.3' 典型值为:“ 3.5.3”

I am using this code which I found online: 我正在使用在网上找到的以下代码:

RegistryKey RegInfo = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\AVG CloudCare", false);

object CCVersionReg = RegInfo.GetValue("DisplayVersion", "0");

Console.WriteLine(CCVersionReg);
Console.ReadLine();

However I always get an error: "Object reference not set to an instance of an object.". 但是,我总是收到一个错误:“对象引用未设置为对象的实例。”。

I tried to convert the object to a string like this: 我试图将对象转换为这样的字符串:

Console.WriteLine(CCVersionReg.ToString);

This also doesn't work, with the error, "Cannot convert to 'method group' from 'bool'. 这也行不通,错误为“无法从'布尔'转换为'方法组'。

The reason I need this is to compare this version with the known latest version for an updater application, which I need to use string to compare the values. 我需要这样做的原因是将该版本与更新程序应用程序的已知最新版本进行比较,我需要使用字符串来比较这些值。

Try this 尝试这个

var key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\AVG CloudCare";
Console.WriteLine(Registry.GetValue(key, "DisplayVersion", "0")?.ToString());

When ToString() is invoked on a null object, it throws Object reference not set to an instance of an object 当对null对象调用ToString() ,它将引发Object reference not set to an instance of an object

Your error 你的错误

Console.WriteLine(CCVersionReg.ToString);

is throwing that error because CCVersion.ToString is a method group. 抛出该错误,因为CCVersion.ToString是方法组。 You will need to invoke the method by doing this: 您将需要通过执行以下操作来调用该方法:

Console.WriteLine(CCVersionReg.ToString());

However, you will get a null reference exception(as you are seeing) if CCVersionReg is null. 但是,如果CCVersionReg为null,则将得到一个null引用异常(如您所见)。 Check that it gets created properly 检查它是否正确创建

Is your application 32-bit running on a 64-bit OS ? 您的应用程序是否在64位OS上运行32位? If so, please see: OpenSubKey() returns null for a registry key that I can see in regedit.exe 如果是这样,请参见: OpenSubKey()对于regedit.exe中可以看到的注册表项返回null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM