【问题标题】:Can I catch a missing dll error during application load in C#?我可以在 C# 中的应用程序加载期间捕获丢失的 dll 错误吗?
【发布时间】:2010-11-09 19:44:14
【问题描述】:

在找不到引用的 .dll 时是否可以捕获异常?

例如,我有一个引用第三方 dll 的 C# 项目;如果找不到该 dll,则会引发异常。异常是 System.IO.FileNotFoundException,但我无法确定在哪里捕获它。以下代码似乎不起作用:

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());
        }
    }
}

【问题讨论】:

    标签: c# .net dll


    【解决方案1】:

    扩展乔希的答案。

    .Net 中的程序集由 CLR 按需加载。通常,在使用来自该程序集的类型的方法进行 JIT 处理之前,不会尝试加载程序集。

    如果您无法在 main 方法中使用 try/catch 块捕获程序集加载失败,这可能是因为您在 try/catch 中使用了程序集中的类型。所以异常发生在main方法实际运行之前。

    尝试将 main 方法中的所有代码放在不同的函数中。然后在 try/catch 块中调用该函数,您应该会看到异常。

    【讨论】:

      【解决方案2】:

      你可以使用AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

        Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
          {
          }
      

      如果无法自动找到程序集,则手动查找程序集。

      【讨论】:

      【解决方案3】:

      对于表单应用程序,将 try/catch 放入 Program.cs。 (扩展 JaredPat 的回答)。

      像这样:

          [STAThread]
          static void Main()
          {
              try
              {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);
                  Application.Run(new Form1());
      
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
                  throw;
              }
          }
      

      这将从您的应用程序中捕获任何丢失的 DLL 异常。它们看起来与此类似:

      无法加载文件或程序集“TheGreatestDLLEver.Tribute”, 版本=0.0.0.2,文化=中性,PublicKeyToken=jamtoastbutter' 或 它的依赖项之一。系统找不到指定的文件。

      【讨论】:

      • 问题是“或其依赖项之一”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多