使用英语阅读

通过


BadImageFormatException 类

定义

当动态链接库 (DLL) 或可执行程序的文件映像无效时引发的异常。

C#
public class BadImageFormatException : Exception
C#
public class BadImageFormatException : SystemException
C#
[System.Serializable]
public class BadImageFormatException : SystemException
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BadImageFormatException : SystemException
继承
BadImageFormatException
继承
BadImageFormatException
属性

注解

当动态链接库 (.dll 文件) 或可执行 (.exe 文件的文件格式) 不符合公共语言运行时所需的格式时,将引发此异常。 具体而言,在以下情况下引发异常:

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

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

  • 您正尝试加载非托管动态链接库或可执行 (,例如 Windows 系统 DLL) ,就像它是 .NET 程序集一样。 下面的示例通过使用 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.
    

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

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

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

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

  • 应用程序的组件是使用不同版本的 .NET 创建的。 通常,当使用 .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 编译器编译源代码,BadImageFormatException则 方法将引发 Assembly.LoadFrom

    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。

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

    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构造函数。

构造函数

BadImageFormatException()

初始化 BadImageFormatException 类的新实例。

BadImageFormatException(SerializationInfo, StreamingContext)

用序列化数据初始化 BadImageFormatException 类的新实例。

BadImageFormatException(String)

用指定的错误消息初始化 BadImageFormatException 类的新实例。

BadImageFormatException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 BadImageFormatException 类的新实例。

BadImageFormatException(String, String)

用指定的错误消息和文件名初始化 BadImageFormatException 类的新实例。

BadImageFormatException(String, String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 BadImageFormatException 类的新实例。

属性

Data

获取键/值对的集合,这些键/值对提供有关该异常的其他用户定义信息。

(继承自 Exception)
FileName

获取导致该异常的文件的名称。

FusionLog

获取描述程序集加载失败的原因的日志文件。

HelpLink

获取或设置指向与此异常关联的帮助文件链接。

(继承自 Exception)
HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。

(继承自 Exception)
InnerException

获取导致当前异常的 Exception 实例。

(继承自 Exception)
Message

获取错误消息和引发此异常的文件的名称。

Source

获取或设置导致错误的应用程序或对象的名称。

(继承自 Exception)
StackTrace

获取调用堆栈上的即时框架字符串表示形式。

(继承自 Exception)
TargetSite

获取引发当前异常的方法。

(继承自 Exception)

方法

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根本原因。

(继承自 Exception)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

用文件名、程序集缓存日志和其他异常信息设置 SerializationInfo 对象。

GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfo

(继承自 Exception)
GetType()

获取当前实例的运行时类型。

(继承自 Exception)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回该异常的完全限定名,还可能返回错误消息、内部异常的名称和堆栈跟踪。

事件

SerializeObjectState
已过时.

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。

(继承自 Exception)

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅