4

我在我的项目中使用 System.Data.SQLite。当输出文件夹中没有 System.Data.SQLite dll 时,我无法捕获 FileNotFoundException(其他异常捕获良好)。这是代码示例:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            SQLiteConnection conn = new SQLiteConnection();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

消息框未显示。如果我在单独的函数中提取此代码并将此函数调用包装在 try catch 中,则捕获异常工作正常并且 MessageBox 显示:

    private void DeclareConnection()
    {
        SQLiteConnection conn = new SQLiteConnection();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            DeclareConnection();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

问题是什么?

4

3 回答 3

3

您将不得不处理AppDomain.AssemblyResolve事件,

订阅 AssemblyResolve 事件

AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve;

这是一些示例代码,用于处理在 c# 中加载 x86 / x64 SQLite 程序集

    public static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args)
    {
        if (args.Name.Contains("System.Data.SQLite"))
        {
            if (_assembliesResolved)
                return null;

            Assembly returnValue;

            string executingAssemblyPath = Assembly.GetExecutingAssembly().Location;
            executingAssemblyPath = Path.GetDirectoryName(executingAssemblyPath);

            if (Environment.Is64BitProcess)
                executingAssemblyPath = Path.Combine(executingAssemblyPath, @"lib-sqlite\x64\", "System.Data.SQLite.dll");
            else //32 bit process
                executingAssemblyPath = Path.Combine(executingAssemblyPath, @"lib-sqlite\x86\", "System.Data.SQLite.dll");

            returnValue = Assembly.LoadFrom(executingAssemblyPath);

            _assembliesResolved = true;

            return returnValue;
        }

        return null;
    }
于 2013-03-04T08:48:35.703 回答
0

您无法捕获因未找到引用程序集而产生的异常。

只有当您使用反射手动加载程序集时,您才能捕获异常。

要检查 sqlite 程序集是否存在,请执行File.Exists().

于 2013-03-04T08:46:17.623 回答
0

在第一种情况下,您无法捕获异常,因为 jit 在遇到方法时立即抛出异常。在第二种情况下,它会 jit 您的方法,并且在尝试 jitDeclareConnection方法时抛出异常。

于 2013-03-04T08:49:56.650 回答