我能赶上过程中C#应用程序负载缺少DLL的错误? [英] Can I catch a missing dll error during application load in C#?

查看:199
本文介绍了我能赶上过程中C#应用程序负载缺少DLL的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能捕获异常时引用的.dll文件找不到?



例如,我有一个第三方DLL的引用的C#项目;如果DLL无法找到,则抛出异常。唯一的例外是System.IO.FileNotFoundException,但我无法确定要抓住它。下面的代码似乎没有工作:

 静态类节目
{
///<总结>
///的主入口点应用程序。
///< /总结>
[STAThread]
静态无效的主要()
{

{
//代码放在这里
}
抓(例外EXC)
{
MessageBox.Show(exc.ToString());
}
}
}


解决方案

扩展Josh的答案。



集加载由CLR需求。典型地装配载荷将不会尝试,直到方法JIT'd其使用从该组件的类型。



如果您不能赶上与主方法的try / catch块大会加载失败,很可能beceause你用从内部装配型try / catch语句。因此,主要方法是实际运行之前发生异常。



尝试把所有的代码从主方法不同的功能。然后调用try / catch块内的功能,你应该看到的例外。


Is it possible to catch the exception when a referenced .dll cannot be found?

For example, I have a C# project with a reference to a third-party dll; if that dll cannot be found, an exception is thrown. The exception is a System.IO.FileNotFoundException, but I am unable to determine where to catch it. The following code did not seem to work:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {
          // code goes here
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.ToString());
        }
    }
}

解决方案

Extending Josh's answer.

Assemblies in .Net are loaded on demand by the CLR. Typically an assembly load won't be attempted until a method is JIT'd which uses a type from that assembly.

If you can't catch the assembly load failure with a try/catch block in the main method, it's likely beceause you're using a type from the assembly within the try/catch. So the exception occurs before the main method is actually run.

Try putting all of the code from the main method in a different function. Then call that function within the try/catch block and you should see the exception.

这篇关于我能赶上过程中C#应用程序负载缺少DLL的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆