C# 捕获异常被忽略,因此应用程序崩溃
C# catch exception being ignored thus application crushes
我需要在 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:'Object reference not set to an instance of an object.' - 这是错误,我知道它发生是因为我 select 一个 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;
}
我需要在 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:'Object reference not set to an instance of an object.' - 这是错误,我知道它发生是因为我 select 一个 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;
}