c# - C# catch 异常被忽略,因此应用程序崩溃
问题描述
我需要在 WinForm C# 中制作一个应用程序作为我的最终编程项目。该项目旨在更好地管理注册表,以使用户更容易编辑值。
问题是,当我读取UninstallString是否存在时,由于某种原因,该函数在失败时不会查看 try 内的 catch (并且由于应用程序不是 64 位而失败,因此注册表值需要以不同的方式访问)
public bool ValueExists(string Key, string Value)
{
try
{
try
{
RegistryKey rk = Registry.LocalMachine.OpenSubKey(Key);
return rk.GetValue(Value) != null; //Error happens here when selected 64-bit application. System.NullReferenceException: 'Object reference not set to an instance of an object.'
}
catch (NullReferenceException ex)
{
RegistryKey regkey64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey rk64 = regkey64.OpenSubKey(Value);
return regkey64.OpenSubKey(Key).GetValue(Value) != null;
}
}
catch
{
return false;
}
}
System.NullReferenceException:“对象引用未设置为对象的实例。” - 这是错误,我知道它的发生是因为我选择了一个 64 位应用程序,但由于某种原因它忽略了捕获。
解决方案
名为Richard Deeming的用户在CodeProject中为我解决了这个问题
他提出了一种完全不同的方法。他不使用 catch,而是检查进程是否为 64 位,这样他指示代码是否强制读取 64 位注册表值(取决于所选程序)。这是他的代码(我做了一个修复):
public bool ValueExists(string Key, string Value)
{
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(Key, false))
{
if (rk != null) return rk.GetValue(Value) != null;
}
if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess)
{
RegistryKey regkey64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
return regkey64.OpenSubKey(Key).GetValue(Value) != null;
}
return false;
}
推荐阅读
- jenkins - Jenkins主从错误:主机密钥验证失败
- c# - 如何将文件 image.tif 加载到图片框中?
- swift - Swift 4 Firebase .childAdded 不检索最新记录
- c++ - 由于花费大量时间,代码未执行
- kubernetes - Cephfs:动态配置不起作用
- javascript - unshift 后的数组长度错误
- excel - 将工作表从一个 Excel 文件导入到另一个而不指定目的地
- regex - 如何使用python构建正确的正则表达式以在txt文件中查找单词?
- android - Android SDK 工具
- reactjs - 由于不再存在的文件中的意外令牌,推送到 Heroku 时构建失败