BadImageFormatException 类

定义

当动态链接库 (DLL) 或可执行程序的文件映像无效时引发的异常。The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.

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

注解

如果动态链接库 (.dll 文件) 或可执行文件 (.exe 文件) 的文件格式不符合公共语言运行时所需的格式, 则会引发此异常。This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) doesn't conform to the format that the common language runtime expects. 具体而言, 在以下情况下会引发异常:In particular, the exception is thrown under the following conditions:

  • 早期版本的 .NET Framework 实用工具 (如 installutil.exe 或) 与使用 .NET Framework 的更高版本开发的程序集一起使用。An earlier version of a .NET Framework utility, such as ILDasm.exe or installutil.exe, is used with an assembly that was developed with a later version of the .NET Framework.

    若要解决此异常, 请使用与用于开发程序集的 .NET Framework 版本相对应的工具版本。To address this exception, use the version of the tool that corresponds to the version of the .NET Framework that was used to develop the assembly. 这可能需要修改Path环境变量或为正确的可执行文件提供完全限定的路径。This may require modifying the Path environment variable or providing a fully qualified path to the correct executable.

  • 尝试加载非托管动态链接库或可执行文件 (如 Windows 系统 DLL), 就像它是 .NET Framework 程序集一样。You are trying to load an unmanaged dynamic link library or executable (such as a Windows system DLL) as if it were a .NET Framework assembly. 下面的示例通过使用Assembly.LoadFile方法加载 kernel32.dll 对此进行了说明。The following example illustrates this by using the Assembly.LoadFile method to load Kernel32.dll.

    // 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.
    
    ' 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的语句DllImportAttribute或中extern C#包含关键字的属性) 访问在 DLL 中定义的方法。To address this exception, access the methods defined in the DLL by using the features provided by your development language, such as the Declare statement in Visual Basic or the DllImportAttribute attribute with the extern keyword in C#.

  • 您尝试在非仅反射上下文中加载引用程序集。You are trying to load a reference assembly in a context other than the reflection-only context. 可以通过以下两种方式之一解决此问题:You can address this issue in either of two ways:

    • 可以加载实现程序集, 而不是引用程序集。You can load the implementation assembly rather than the reference assembly.
    • 您可以通过调用Assembly.ReflectionOnlyLoad方法在只反射上下文中加载引用程序集。You can load the reference assembly in the reflection-only context by calling the Assembly.ReflectionOnlyLoad method.
  • DLL 或可执行文件作为64位程序集加载, 但包含32位功能或资源。A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources. 例如, 它依赖于 COM 互操作或在32位动态链接库中调用方法。For example, it relies on COM interop or calls methods in a 32-bit dynamic link library.

    若要解决此异常, 请将项目的 "平台目标" 属性设置为 x86 (而不是 X64 或 AnyCPU) 并重新编译。To address this exception, set the project's Platform target property to x86 (instead of x64 or AnyCPU) and recompile.

  • 应用程序的组件是使用 .NET Framework 的不同版本创建的。Your application's components were created using different versions of the .NET Framework. 通常, 在使用.NET Framework 1.0.NET Framework 1.0 .NET Framework 1.1.NET Framework 1.1或更高版本开发的应用程序或组件尝试加载使用.NET Framework 2.0 SP1.NET Framework 2.0 SP1或更高版本开发的程序集时, 或者当使用或尝试加载使用.NET Framework 4.NET Framework 4或更高版本开发的程序集。 .NET Framework 3.5.NET Framework 3.5 .NET Framework 2.0 SP1.NET Framework 2.0 SP1Typically, this exception occurs when an application or component that was developed using the .NET Framework 1.0.NET Framework 1.0 or the .NET Framework 1.1.NET Framework 1.1 tries to load an assembly that was developed using the .NET Framework 2.0 SP1.NET Framework 2.0 SP1 or later, or when an application that was developed using the .NET Framework 2.0 SP1.NET Framework 2.0 SP1 or .NET Framework 3.5.NET Framework 3.5 tries to load an assembly that was developed using the .NET Framework 4.NET Framework 4 or later. BadImageFormatException可能会被报告为编译时错误, 或者在运行时可能会引发异常。The BadImageFormatException may be reported as a compile-time error, or the exception may be thrown at run time. 下面的示例定义StringLib了一个类, 该类包含一个名为 StringLib 的程序集中的成员、 ToProperCase和。The following example defines a StringLib class that has a single member, ToProperCase, and that resides in an assembly named 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.
    
    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 的程序集。The following example uses reflection to load an assembly named StringLib.dll. 如果源代码是用.NET Framework 1.1.NET Framework 1.1编译器编译的BadImageFormatException , 则Assembly.LoadFrom方法会引发。If the source code is compiled with a .NET Framework 1.1.NET Framework 1.1 compiler, a BadImageFormatException is thrown by the Assembly.LoadFrom method.

    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);
       }
    }
    
    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 Framework 目标兼容版本的程序集。To address this exception, make sure that the assembly whose code is executing and that throws the exception, and the assembly to be loaded both target compatible versions of the .NET Framework.

  • 应用程序的组件面向不同的平台。The components of your application target different platforms. 例如, 你要尝试在 x86 应用程序中加载 ARM 程序集。For example, you are trying to load ARM assemblies in an x86 application. 您可以使用以下命令行实用程序来确定单个 .NET Framework 程序集的目标平台。You can use the following command-line utility to determine the target platforms of individual .NET Framework assemblies. 文件列表应在命令行中以空格分隔的列表形式提供。The list of files should be provided as a space-delimited list at the command line.

    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");
                }
             }
          }
       }
    }
    
    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++ 可执行文件进行反射可能会引发此异常。Reflecting on C++ executable files may throw this exception. 这极有可能是因为 C++ 编译器从可执行文件中剥离重定位地址或 .Reloc 节引起的。This is most likely caused by the C++ compiler stripping the relocation addresses or the .Reloc section from the executable file. 若要在C++可执行文件中保留重定位地址, 请在链接时指定/fixed: no。To preserve the .relocation address in a C++ executable file, specify /fixed:no when linking.

BadImageFormatException使用 COR_E_BADIMAGEFORMAT 值为0x8007000B 的 HRESULT。BadImageFormatException uses the HRESULT COR_E_BADIMAGEFORMAT, which has the value 0x8007000B.

有关实例的初始属性值的列表BadImageFormatException,请参阅BadImageFormatException构造函数。For a list of initial property values for an instance of BadImageFormatException, see the BadImageFormatException constructors.

构造函数

BadImageFormatException()

初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class.

BadImageFormatException(SerializationInfo, StreamingContext)

用序列化数据初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class with serialized data.

BadImageFormatException(String)

用指定的错误消息初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class with a specified error message.

BadImageFormatException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class with a specified error message and a reference to the inner exception that is the cause of this exception.

BadImageFormatException(String, String)

用指定的错误消息和文件名初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class with a specified error message and file name.

BadImageFormatException(String, String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 BadImageFormatException 类的新实例。Initializes a new instance of the BadImageFormatException class with a specified error message and a reference to the inner exception that is the cause of this exception.

属性

Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(继承自 Exception)
FileName

获取导致该异常的文件的名称。Gets the name of the file that causes this exception.

FusionLog

获取描述程序集加载失败的原因的日志文件。Gets the log file that describes why an assembly load failed.

HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(继承自 Exception)
HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(继承自 Exception)
InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(继承自 Exception)
Message

获取错误消息和引发此异常的文件的名称。Gets the error message and the name of the file that caused this exception.

Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(继承自 Exception)
StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(继承自 Exception)
TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(继承自 Exception)

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(继承自 Exception)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

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

用文件名、程序集缓存日志和其他异常信息设置 SerializationInfo 对象。Sets the SerializationInfo object with the file name, assembly cache log, and additional exception information.

GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(继承自 Exception)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回该异常的完全限定名,还可能返回错误消息、内部异常的名称和堆栈跟踪。Returns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace.

事件

SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(继承自 Exception)

适用于

另请参阅