FileNotFoundExceptions for System.Data.SQLite not hooked

I am using System.Data.SQLite in my project. When the System.Data.SQLite DLL is not in the output folder, I cannot catch a FileNotFoundException (another exception is caught). Here is the exapmle code:

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

MessageBox is not displayed. If I extract this code into a separate function and end this function call in try catch, and the catch exception will fail, the MessageBox will show:

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

What is the problem?

+4
source share
3 answers

You will need to handle the AppDomain.AssemblyResolve event,

Subscribe to AssemblyResolve event

 AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve; 

Here is a sample code that handles loading SQLite x86 / x64 collections in C #

  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; } 
+3
source

You cannot catch exceptions that are created because the referenced assembly is not found.

Only if you manually load the assembly using Reflection can you catch an exception.

To check if the sqlite assembly exists, do File.Exists() .

0
source

In the first case, you cannot catch an exception because jit throws an exception as soon as it hits the method. In the second case, it compresses your method, and an exception is thrown by the time it tries to use the DeclareConnection method.

0
source

All Articles