Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 未捕获System.Data.SQLite的FileNotFoundExceptions_C#_Sqlite - Fatal编程技术网

C# 未捕获System.Data.SQLite的FileNotFoundExceptions

C# 未捕获System.Data.SQLite的FileNotFoundExceptions,c#,sqlite,C#,Sqlite,我在项目中使用System.Data.SQLite。当输出文件夹中没有System.Data.SQLite dll时,我无法捕获FileNotFoundException(捕获的其他异常很好)。以下是代码示例: private void button1_Click(object sender, RoutedEventArgs e) { try { SQLiteConnection conn = new SQLiteConne

我在项目中使用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);
        }
    }
MessageBox没有显示。如果我在单独的函数中提取此代码,并在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);
        }
    }

问题是什么?

您无法捕获由于找不到引用的程序集而生成的异常

只有手动加载带有反射的程序集,才能捕获异常


要检查sqlite程序集是否存在,请执行一个
文件.Exists()

您必须处理该事件

订阅AssemblyResolve事件

AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve;
下面是一些处理在c中加载x86/x64 SQLite程序集的示例代码#


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

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