C# 未捕获System.Data.SQLite的FileNotFoundExceptions
我在项目中使用System.Data.SQLite。当输出文件夹中没有System.Data.SQLite dll时,我无法捕获FileNotFoundException(捕获的其他异常很好)。以下是代码示例: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
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;
}