加载DLL时的C#异常。无法找到解决方案

时间:2014-05-05 01:55:37

标签: c# dll reflection

我在DLL运行时加载C#时遇到了问题。

以下代码:

foreach (var f in Directory.EnumerateFiles(startFolder, "*.dll",            SearchOption.AllDirectories))
{
   try
   {
       var assembly = Assembly.LoadFrom(f);
       var types = assembly.GetTypes(); //exception raised here

       foreach (var type in types)
       {
            if (type.GetInterface("IPlayerFactory") != null)
                 instances.Add((IPlayerFactory)Activator.CreateInstance(type));
       }
       assembly = null;
    }
    catch (ReflectionTypeLoadException ex) { /* later, keep reading  */}

所以例外说:

An exception of type 'System.Reflection.ReflectionTypeLoadException' occurred in
mscorlib.dll but was not handled in user code

Additional information: Unable to load one or more of the requested types. Retrieve the    
LoaderExceptions property for more information.

我搜索了一下堆栈,发现这个catch寻找更多信息(来源:here

catch block:

catch (ReflectionTypeLoadException ex)
{
     StringBuilder sb = new StringBuilder();
     foreach (Exception exSub in ex.LoaderExceptions)
     {
          sb.AppendLine(exSub.Message);
          FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
          if (exFileNotFound != null)
          {
              if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
              {
                  sb.AppendLine("Fusion Log:");
                  sb.AppendLine(exFileNotFound.FusionLog);
              }
          }
                    sb.AppendLine();
      }
      string errorMessage = sb.ToString();
      //Display or log the error based on your application.
      Console.WriteLine(sb);
 }

所以我设法提取:

'Battleships.Desktop.vshost.exe' (CLR v4.0.30319: Battleships.Desktop.vshost.exe):
 Loaded 'C:\SomePath\some_dll.dll'. Cannot find
 or open the PDB file.
 A first chance exception of type 'System.Reflection.ReflectionTypeLoadException'  
 occurred in mscorlib.dll

我尝试了一些解决方案,但没有任何效果。 有什么新鲜的想法吗?

2 个答案:

答案 0 :(得分:3)

在调试模式下构建代码时,会创建两个文件,一个是类库,另一个是' debug database' .pdb文件。如果您在调试模式下运行代码,请在反射代码的bin中包含pdb文件。 另一件事是在命令提示符下使用fuslogvw查看Fusion日志。它可能会给出任何未处理的运行时故障/依赖项。

答案 1 :(得分:0)

在发布模式下,我收到相同的奥术错误(“无法加载一个或多个请求的类型。获取LoaderExceptions属性以获取更多信息”),因此amolDotnet的解决方案不适用于我的情况。为了使其他偶然发现相同问题的人受益,我将指出我设法通过添加DLL需要的缺失的Nuget包依赖关系来对其进行修复。 T以前已经在Nuget软件包控制台中关闭了依赖项警告,并且DLL的功能还不错,直到我尝试加载程序集并通过Reflection检查成员。如果krzakov没有提到对异常信息的深入检查,我可能找不到这种替代解决方案。