-1

When a DLL file is deleted, the app crashes before the Main method. In Windows Event Viewer, it shows "...System.IO.FileNotFoundException ".

How can I handle this exception in the application?

My present code:

static void Main(string[] args)
    {        
        if (!File.Exists("PCSQL.dll")) 
        { 
            AppendLaunchErrorLog("*PCSQL.dll file doesn't exist*");               
            Environment.Exit(0); 
        }

        ...
  • 1
    how are the Dll's getting Deleted to begin with would be my first / major concern & || Question you could also do a simple google search on the following [AppDomain.AssemblyResolve Event](https://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) – MethodMan Jan 19 '16 at 20:22
  • Is this native or managed dll? – csharpfolk Jan 19 '16 at 20:23
  • @MethodMan The app is still in development and will be share on a server, I am just trying to image a situation where an update went wrong or an administrator deleted by mistake a DLL file. –  Jan 19 '16 at 20:25
  • @MethodMan AppDomain.AssemblyResolve Event : Occurs when the resolution of an assembly fails. I want to handle a missing file (referenced DLL) exception that happens before the main method. –  Jan 19 '16 at 20:37
  • The DLL method ( new AtLaunch().Verification(); ) is called after checking for the existence of the DLL file. I had to call this DLL method inside a method of the main class to make it work. It just seems that every line of code within the Main method is verified before being applied. Can anybody explain this in an answer? Thanks –  Jan 20 '16 at 14:51

2 Answers2

0

I believe the way to do that would be not from within the program but from a separate program which would check for this and then Invoke Main method or trigger this program. This separate program can catch the exception as it is not occurring in it.

lazy
  • 531
  • 2
  • 4
0

As this is native DLL invoked via P/Invoke mechanism, program will work until first invocation of method that is implemented in that DLL.

You can catch exceptions thrown by P/Invoke and then react to it like to any other exception (show message to use, log error, do some custom logi etc.). Good list of P/Invoke exception can be found in this answer.

Alternatively you may bypass P/Invoke and use old-school WinAPI LoadLibrary and GetProcAddress to invoke functions from DLL example here. There will be no exceptions, you must manually check return codes from functions.

You may also combine this two aproaches, use LoadLibrary to check if DLL exists and is loadable by .NET, and use P/Invoke to interact with that DLL.

Community
  • 1
  • 1
csharpfolk
  • 4,124
  • 25
  • 31