【问题标题】:C# catch exception being ignored thus application crushesC# catch 异常被忽略,因此应用程序崩溃
【发布时间】:2020-11-04 23:02:21
【问题描述】:

我需要在 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 位应用程序,但由于某种原因它忽略了捕获。

【问题讨论】:

  • 获取发生这种情况的堆栈跟踪
  • 在该行放置一个断点。 rk 是否为空?如果是这样,为什么并处理它。
  • 这是不可读的,因为它是一个 64 位的注册表值(意思是,如果我选择一个 32 位的应用程序,这个异常就不会发生),所以我做了这个异常。我还能做些什么来处理它?
  • rk 也为空?
  • 您是如何将应用程序设置为 64 位的?你能显示代码/项目吗?你确定rk 为空(使用调试器)?

标签: c# try-catch registry


【解决方案1】:

名为 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多