首页 > 解决方案 > 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 位应用程序,但由于某种原因它忽略了捕获。

标签: c#try-catchregistry

解决方案


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

推荐阅读