BadImageFormatException 类

定义

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

public ref class BadImageFormatException : Exception
public ref class BadImageFormatException : SystemException
public class BadImageFormatException : Exception
public class BadImageFormatException : SystemException
[System.Serializable]
public class BadImageFormatException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BadImageFormatException : SystemException
type BadImageFormatException = class
    inherit Exception
type BadImageFormatException = class
    inherit SystemException
[<System.Serializable>]
type BadImageFormatException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type BadImageFormatException = class
    inherit SystemException
Public Class BadImageFormatException
Inherits Exception
Public Class BadImageFormatException
Inherits SystemException
继承
BadImageFormatException
继承
BadImageFormatException
属性

注解

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

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

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

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

    // 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.
    
    open System
    open System.Reflection
    
    // Windows DLL (non-.NET assembly)
    let filePath = 
        let filePath = Environment.ExpandEnvironmentVariables "%windir%"
        let filePath =
            if not (filePath.Trim().EndsWith @"\") then
                filePath + @"\"
            else filePath
        filePath + @"System32\Kernel32.dll"
    
    try
        Assembly.LoadFile filePath |> ignore
    with :? BadImageFormatException as e ->
       printfn $"Unable to load {filePath}."
       printfn $"{e.Message[0 .. e.Message.IndexOf '.']}"
    
    // The example displays an error message like the following:
    //       Unable to load C:\WINDOWS\System32\Kernel32.dll.
    //       Bad IL format.
    
    ' Windows DLL (non-.NET assembly)
    Dim filePath As String = Environment.ExpandEnvironmentVariables("%windir%")
    If Not filePath.Trim().EndsWith("\") Then filepath += "\"
    filePath += "System32\Kernel32.dll"
    Try
       Dim assem As Assembly = Assembly.LoadFile(filePath)
    Catch e As BadImageFormatException
       Console.WriteLine("Unable to load {0}.", filePath)
       Console.WriteLine(e.Message.Substring(0, _
                         e.Message.IndexOf(".") + 1))   
    End Try
    ' 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.
    

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

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

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

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

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

    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.
    
    open System
    
    module StringLib =
        let private exceptionList = [ "a"; "an"; "the"; "in"; "on"; "of" ]
        let private separators = [| ' ' |]
    
        [<CompiledName "ToProperCase">]
        let toProperCase (title: string) =
            title.Split(separators, StringSplitOptions.RemoveEmptyEntries)
            |> Array.mapi (fun i word ->
                if i <> 0 && List.contains word exceptionList then
                    word
                else 
                    word[0..0].ToUpper() + word[1..])
            |> String.concat " "
    
    // Attempting to load the StringLib.dll assembly produces the following output:
    //    Unhandled Exception: System.BadImageFormatException:
    //                         The format of the file 'StringLib.dll' is invalid.
    
    Public Module StringLib
       Private exceptionList() As String = { "a", "an", "the", "in", "on", "of" }
       Private separators() As Char = { " "c }
       
       Public Function ToProperCase(title As String) As String
          Dim isException As Boolean = False	
          
          Dim words() As String = title.Split( separators, StringSplitOptions.RemoveEmptyEntries)
          Dim newWords(words.Length) As String
            
          For ctr As Integer = 0 To words.Length - 1
             isException = False
    
             For Each exception As String In exceptionList
                If words(ctr).Equals(exception) And ctr > 0 Then
                   isException = True
                   Exit For
                End If
             Next
             If Not isException Then
                newWords(ctr) = words(ctr).Substring(0, 1).ToUpper() + words(ctr).Substring(1)
             Else
                newWords(ctr) = words(ctr)	 
             End If	 
          Next	
          Return String.Join(" ", newWords) 			
       End Function
    End Module
    

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

    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);
       }
    }
    
    open System.Reflection
    
    let title = "a tale of two cities"
          
    // Load assembly containing StateInfo type.
    let assem = Assembly.LoadFrom @".\StringLib.dll"
    
    // Get type representing StateInfo class.
    let stateInfoType = assem.GetType "StringLib"
    
    // Get Display method.
    let mi = stateInfoType.GetMethod "ToProperCase"
    
    // Call the Display method.
    let properTitle = 
       mi.Invoke(null, [| box title |]) :?> string
    
    printfn $"{properTitle}"
    
    Imports System.Reflection
    
    Module Example
       Public Sub Main()
          Dim title As String = "a tale of two cities"
          ' Load assembly containing StateInfo type.
          Dim assem As Assembly = Assembly.LoadFrom(".\StringLib.dll")
          ' Get type representing StateInfo class.
          Dim stateInfoType As Type = assem.GetType("StringLib")
          ' Get Display method.
          Dim mi As MethodInfo = stateInfoType.GetMethod("ToProperCase")
          ' Call the Display method. 
          Dim properTitle As String = CStr(mi.Invoke(Nothing, New Object() { title } ))
          Console.WriteLine(properTitle)
       End Sub
    End Module
    ' Attempting to load the StringLib.dll assembly produces the following output:
    '    Unhandled Exception: System.BadImageFormatException: 
    '                         The format of the file 'StringLib.dll' is invalid.
    

    若要解决此异常,请确保执行代码并引发异常的程序集以及要加载的程序集,这两个目标兼容版本的 .NET。

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

    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");
                }
             }
          }
       }
    }
    
    open System
    open System.IO
    open System.Reflection
    
    let args = Environment.GetCommandLineArgs()
    
    if args.Length = 1 then
        printfn "\nSyntax:   PlatformInfo <filename>\n"
    else
        printfn ""
        // Loop through files and display information about their platform.
        for i = 1 to args.Length - 1 do
            let fn = args[i]
            if not (File.Exists fn) then
                printfn $"File: {fn}"
                printfn "The file does not exist.\n"
            else
                try
                    let an = AssemblyName.GetAssemblyName fn
                    printfn $"Assembly: {an.Name}"
                    if an.ProcessorArchitecture = ProcessorArchitecture.MSIL then
                        printfn "Architecture: AnyCPU"
                    else
                        printfn $"Architecture: {an.ProcessorArchitecture}"
                    printfn ""
    
                with :? BadImageFormatException ->
                    printfn $"File: {fn}"
                    printfn "Not a valid assembly.\n"
    
    Imports System.IO
    Imports System.Reflection
    
    Module Example
       Public Sub Main()
          Dim args() As String = Environment.GetCommandLineArgs()
          If args.Length = 1 Then
             Console.WriteLine()
             Console.WriteLine("Syntax:   PlatformInfo <filename> ")
             Console.WriteLine()
             Exit Sub
          End If
          Console.WriteLine()
          
          ' Loop through files and display information about their platform.
          For ctr As Integer = 1 To args.Length - 1
             Dim fn As String = args(ctr)
             If Not File.Exists(fn) Then
                Console.WriteLine("File: {0}", fn)
                Console.WriteLine("The file does not exist.")
                Console.WriteLine()
             Else
                Try
                   Dim an As AssemblyName = AssemblyName.GetAssemblyName(fn)
                   Console.WriteLine("Assembly: {0}", an.Name)
                   If an.ProcessorArchitecture = ProcessorArchitecture.MSIL Then
                      Console.WriteLine("Architecture: AnyCPU")
                   Else
                      Console.WriteLine("Architecture: {0}", an.ProcessorArchitecture)
                   End If
                Catch e As BadImageFormatException
                   Console.WriteLine("File: {0}", fn)
                   Console.WriteLine("Not a valid assembly.\n")
                End Try
                Console.WriteLine()
             End If
          Next
       End Sub
    End Module
    
  • 反映 C++ 可执行文件可能会引发此异常。 这很可能是由 C++ 编译器去除重定位地址或重定位地址引起的。从可执行文件重新定位部分。 若要在 C++ 可执行文件中保留 .relocation 地址,请在链接时指定 /fixed:no。

BadImageFormatException 使用具有值0x8007000B的 HRESULT COR_E_BADIMAGEFORMAT

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

构造函数

名称 说明
BadImageFormatException()

初始化 BadImageFormatException 类的新实例。

BadImageFormatException(SerializationInfo, StreamingContext)
已过时.

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

BadImageFormatException(String, Exception)

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

BadImageFormatException(String, String, Exception)

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

BadImageFormatException(String, String)

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

BadImageFormatException(String)

使用指定的错误消息初始化类的新实例 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使用文件名、程序集缓存日志和其他异常信息设置对象。

GetType()

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

(继承自 Exception)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

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

活动

名称 说明
SerializeObjectState
已过时.

序列化异常以创建包含有关异常的序列化数据的异常状态对象时发生。

(继承自 Exception)

适用于

另请参阅