C# 获取C中某个程序的卸载命令#
所以我正在编写这段代码,它返回一个卸载命令字符串来卸载某个程序。 我在其他问题中看到过这段代码,但似乎没有人和我有同样的问题。 代码如下:C# 获取C中某个程序的卸载命令#,c#,registrykey,C#,Registrykey,所以我正在编写这段代码,它返回一个卸载命令字符串来卸载某个程序。 我在其他问题中看到过这段代码,但似乎没有人和我有同样的问题。 代码如下: public static string GetUninstallCommandFor(string productDisplayName) { RegistryKey localMachine = Registry.LocalMachine; string productsRoot = @"SOFTWARE
public static string GetUninstallCommandFor(string productDisplayName)
{
RegistryKey localMachine = Registry.LocalMachine;
string productsRoot = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products";
RegistryKey products = localMachine.OpenSubKey(productsRoot);
string[] productFolders = products.GetSubKeyNames();
foreach (string p in productFolders)
{
RegistryKey installProperties = products.OpenSubKey(p + @"\InstallProperties");
if (installProperties != null)
{
string displayName = (string)installProperties.GetValue("DisplayName");
if ((displayName != null) && (displayName.Contains(productDisplayName)))
{
string uninstallCommand = (string)installProperties.GetValue("UninstallString");
return uninstallCommand;
}
}
}
return "";
}
此代码返回以下错误:
System.NullReferenceException:“对象引用未设置为对象的实例。”
产品为空
我不知道产品怎么可能是空的,我确实检查了子项,子项中充满了文件夹,因此如何解决这个问题。为X64构建。在32位进程中,您实际上是在通过读取
HKEY\u LOCAL\u MACHINE\Software\Wow6432Node
或者,您可以通过以下方式请求注册表的未重定向视图:
为X64构建。在32位进程中,您实际上是在通过读取
HKEY\u LOCAL\u MACHINE\Software\Wow6432Node
或者,您可以通过以下方式请求注册表的未重定向视图:
给定该错误消息,
产品
不为空的可能性为零。所以你需要找出为什么localMachine.OpenSubKey(productsRoot)
没有返回任何内容。给定该错误消息,产品
不为空的可能性为零。所以你需要找出为什么localMachine.OpenSubKey(productsRoot)
没有返回任何内容。我想我应该设计OpenSubKey
,这样它会抛出一个有意义的异常,而不是默默地什么都不返回。很抱歉,回复太晚了,我将阅读您给我的链接,并将返回给您。@RobertHarvey同意。它应该使用“TryParse模式”,例如bool TryOpenSubKey(KeyName,out RegistryKey)
,如果他们想避免抛出异常,但我认为这种模式直到.NET 2.0才真正出现。我认为我应该设计OpenSubKey
,这样它就会抛出一个有意义的异常,而不是默默地什么也不返回。很抱歉,我会很晚才回复你。我将阅读你给我的链接,然后再回复你。@RobertHarvey同意。如果他们想避免抛出异常,它应该使用“TryParse模式”,例如bool TryOpenSubKey(KeyName,out RegistryKey)
,但我认为该模式直到.NET 2.0才真正出现。