[英]FileNotFoundExceptions for System.Data.SQLite not catched
我在我的項目中使用System.Data.SQLite。 當輸出文件夾中沒有System.Data.SQLite dll時,我無法捕獲FileNotFoundException(其他異常捕獲正常)。 這是代碼exapmle:
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);
}
}
問題是什么?
您將不得不處理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;
}
您無法捕獲由於未找到引用的程序集而生成的異常。
僅當您使用Reflection手動加載程序集時,才能捕獲異常。
要檢查sqlite程序集是否存在,請執行File.Exists()
。
在第一種情況下,您無法捕獲異常,因為jit在遇到方法時會立即拋出異常。 在第二種情況下,它會運行您的方法,並在嘗試jit DeclareConnection
方法時拋出異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.