During testing of a command line based program I delibrately removed a DLL from the execution directory. This of course caused the Could not load file or assembly exception to trigger when the program started, and dumped the raw exception details onto the command line:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'MyDLL, Version=1.2.3.14056, Culture =neutral, PublicKeyToken=0a0932194e205074' or one of its dependencies. The system cannot find the file specified. at MyApp.Program.Program.Main(String[] args)

I don't want the user to see these raw details, but I can't see how/where to catch this exception in order to sanitize the presented message.

So what is the best/accepted way to catch something like this?

有帮助吗?

解决方案

You can register to the Unhandled Exception handler and treat it like so:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((x, y) =>
{
    var exception = y.ExceptionObject as Exception;

    if (exception is System.IO.FileNotFoundException)
        Console.WriteLine("Please make sure the DLL is in the same folder.");
});

Make sure this event registration is executed before any reference to MyDLL in your code. A static constructor in Program.cs might be a good option.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top