c# - 如何拦截 "Could not load file or assembly"?

标签 c# exception clr

在测试基于命令行 的程序时,我故意从执行目录中删除了一个 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/

相关文章:

.net - 如何在运行时检测 .NET 4.5 版当前正在运行您的代码?

c# - 如何防止 NHibernate 长时间运行的进程锁定网站?

c# - 是否使用另一个列表复制值或引用初始化了通用列表?

java - 无法定位错误源

c# - CLR 是如何进行内存管理的

c# - 无法使用/clr 选项从 Visual C++ 项目加载 CLR

c# - 异常代码,或检测到 "file already exists"类型的异常

c# - Windows Phone 8 C# 应用程序中未调用静态字段初始值设定项

java - 当我尝试编译我的 Java 代码时,为什么会得到 "Exception; must be caught or declared to be thrown"?

java - 异常处理冒险 III - 更新