C# System.BadImageFormatException 解决方法

当动态链接库(.dll文件)或可执行文件(.exe文件)的文件格式不符合公共语言运行库期望的格式时,将引发此异常。特别是,在以下情况下会引发异常:

  • .NET Framework实用程序的早期版本(例如ILDasm.exe或installutil.exe)与通过更高版本的.NET Framework开发的程序集一起使用。

    若要解决此异常,请使用与用于开发程序集的.NET Framework版本相对应的工具版本。这可能需要修改Path环境变量或提供指向正确可执行文件的完全限定路径。

  • 您试图加载非托管动态链接库或可执行文件(例如Windows系统DLL),就像它是.NET Framework程序集一样。下面的示例通过使用Assembly.LoadFile方法加载Kernel32.dll来说明这一点。

    C#复制
     
    // Windows DLL (non-.NET assembly)
    string filePath = Environment.ExpandEnvironmentVariables("%windir%");
    if (! filePath.Trim().EndsWith(@"\"))
       filePath += @"\";
    filePath += @"System32\Kernel32.dll";
    
    try {
       Assembly assem = Assembly.LoadFile(filePath);
    }
    catch (BadImageFormatException e) {
       Console.WriteLine("Unable to load {0}.", filePath);
       Console.WriteLine(e.Message.Substring(0,
                         e.Message.IndexOf(".") + 1));
    }
    // The example displays an error message like the following:
    //       Unable to load C:\WINDOWS\System32\Kernel32.dll.
    //       The module was expected to contain an assembly manifest.
    

    若要解决此异常,请使用开发语言提供的功能(例如DeclareVisual Basic中的语句或C#中带有关键字的DllImportAttribute属性)访问DLL中定义的方法extern

  • 您试图在除仅反射上下文之外的上下文中加载参考程序集。您可以通过以下两种方式之一解决此问题:

    • 您可以加载实现程序集而不是参考程序集。
    • 您可以通过调用Assembly.ReflectionOnlyLoad方法在仅反射的上下文中加载参考程序集。
  • DLL或可执行文件以64位程序集的形式加载,但包含32位功能或资源。例如,它依赖于COM互操作或调用32位动态链接库中的方法。

    要解决此异常,请将项目的Platform target属性设置为x86(而不是x64或AnyCPU)并重新编译。

  • 应用程序的组件是使用.NET Framework的不同版本创建的。通常,当使用.NET Framework 1.0或.NET Framework 1.1开发的应用程序或组件尝试加载使用.NET Framework 2.0 SP1或更高版本开发的程序集时,或者当开发了应用程序时,会发生此异常。使用.NET Framework 2.0 SP1或.NET Framework 3.5尝试加载使用.NET Framework 4或更高版本开发的程序集。该BadImageFormatException可能被报告为编译时错误或异常可以在运行时被抛出。下面的示例定义一个StringLib类,该类具有单个成员ToProperCase,并且位于名为StringLib.dll的程序集中。

    C#复制
     
    using System;
    
    public class StringLib
    {
       private string[] exceptionList = { "a", "an", "the", "in", "on", "of" };
       private char[] separators = { ' ' };
    
       public string ToProperCase(string title)
       {
          bool isException = false;	
    
          string[] words = title.Split( separators, StringSplitOptions.RemoveEmptyEntries);
          string[] newWords = new string[words.Length];
            
          for (int ctr = 0; ctr <= words.Length - 1; ctr++)
          {
             isException = false;
    
             foreach (string exception in exceptionList)
             {
                if (words[ctr].Equals(exception) && ctr > 0)
                {
                   isException = true;
                   break;
                }
             }
    
             if (! isException)
                newWords[ctr] = words[ctr].Substring(0, 1).ToUpper() + words[ctr].Substring(1);
             else
                newWords[ctr] = words[ctr];	
          }	
          return String.Join(" ", newWords); 			
       }
    }
    // Attempting to load the StringLib.dll assembly produces the following output:
    //    Unhandled Exception: System.BadImageFormatException:
    //                         The format of the file 'StringLib.dll' is invalid.
    

    下面的示例使用反射加载名为StringLib.dll的程序集。如果源代码是使用.NET Framework 1.1编译器编译的,则Assembly.LoadFrom方法将引发BadImageFormatException

    C#复制
     
    using System;
    using System.Reflection;
    
    public class Example
    {
       public static void Main()
       {
          string title = "a tale of two cities";
    //      object[] args = { title}
          // Load assembly containing StateInfo type.
          Assembly assem = Assembly.LoadFrom(@".\StringLib.dll");
          // Get type representing StateInfo class.
          Type stateInfoType = assem.GetType("StringLib");
          // Get Display method.
          MethodInfo mi = stateInfoType.GetMethod("ToProperCase");
          // Call the Display method.
          string properTitle = (string) mi.Invoke(null, new object[] { title } );
          Console.WriteLine(properTitle);
       }
    }
    

    若要解决此异常,请确保其代码正在执行并且引发了该异常的程序集以及要加载的程序集均面向.NET Framework的两个兼容版本。

  • 您的应用程序的组件针对不同的平台。例如,您试图在x86应用程序中加载ARM程序集。您可以使用以下命令行实用工具来确定单个.NET Framework程序集的目标平台。文件列表应在命令行以空格分隔的列表形式提供。

    C#复制
     
    using System;
    using System.IO;
    using System.Reflection;
    
    public class Example
    {
       public static void Main()
       {
          String[] args = Environment.GetCommandLineArgs();
          if (args.Length == 1) {
             Console.WriteLine("\nSyntax:   PlatformInfo <filename>\n");
             return;
          }
          Console.WriteLine();
    
          // Loop through files and display information about their platform.
          for (int ctr = 1; ctr < args.Length; ctr++) {
             string fn = args[ctr];
             if (! File.Exists(fn)) {
                Console.WriteLine("File: {0}", fn);
                Console.WriteLine("The file does not exist.\n");
             }
             else {
                try {
                   AssemblyName an = AssemblyName.GetAssemblyName(fn);
                   Console.WriteLine("Assembly: {0}", an.Name);
                   if (an.ProcessorArchitecture == ProcessorArchitecture.MSIL)
                      Console.WriteLine("Architecture: AnyCPU");
                   else
                      Console.WriteLine("Architecture: {0}", an.ProcessorArchitecture);
    
                   Console.WriteLine();
                }
                catch (BadImageFormatException) {
                   Console.WriteLine("File: {0}", fn);
                   Console.WriteLine("Not a valid assembly.\n");
                }
             }
          }
       }
    }
    
  • 反思C ++可执行文件可能会引发此异常。这很可能是由C ++编译器从可执行文件中剥离重定位地址或.Reloc节引起的。要在C ++可执行文件中保留.relocation地址,请在链接时指定/ fixed:no。

BadImageFormatException使用HRESULT COR_E_BADIMAGEFORMAT,其值为0x8007000B。

有关BadImageFormatException实例的初始属性值的列表,请参见BadImageFormatException构造函数。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值