在测试基于命令行 的程序时,我故意从执行目录中删除了一个 DLL。这当然会导致程序启动时触发Could not load file or assembly
异常,并将原始异常详细信息转储到命令行:
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)
我不希望用户看到这些原始细节,但我看不到如何/在何处捕获此异常以清理显示的消息。
那么捕捉这样的东西的最佳/可接受的方法是什么?
最佳答案
您可以注册到未处理的异常处理程序并像这样对待它:
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.");
});
确保在您的代码中对 MyDLL
的任何引用之前执行此事件注册。 Program.cs
中的静态构造函数可能是一个不错的选择。
关于c# - 如何拦截 "Could not load file or assembly"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22172666/