BadImageFormatException BadImageFormatException BadImageFormatException BadImageFormatException Class

定義

當動態連結程式庫 (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
繼承
BadImageFormatExceptionBadImageFormatExceptionBadImageFormatExceptionBadImageFormatException
屬性

備註

當動態連結程式庫 (.dll 檔案) 或可執行檔 (.exe 檔) 的檔案格式不符合 common language runtime 所預期的格式,則會擲回這個例外狀況。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 公用程式,例如 ILDasm.exe 或 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.
    

    若要解決這個例外狀況,存取使用的功能,提供您的開發語言,例如在 DLL 中定義的方法Declare在 Visual Basic 中的陳述式或DllImportAttribute屬性搭配externC# 中的關鍵字。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.
  • 為 64 位元組件,載入的 DLL 或可執行檔,但它包含 32 位元的功能或資源。A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources. 比方說,它會依賴的 32 位元動態連結程式庫中的 COM interop 或呼叫方法。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 2.0 SP1.NET Framework 2.0 SP1或是.NET Framework 3.5.NET Framework 3.5嘗試載入組件使用開發.NET Framework 4.NET Framework 4或更新版本。Typically, 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類別具有單一成員, ToProperCase,及位於名為 StringLib.dll 組件中。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.dll 組件。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 會使用 HRESULT COR_E_BADIMAGEFORMAT,其發生於 hresult:0x8007000b 值。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() BadImageFormatException() BadImageFormatException()

初始化 BadImageFormatException 類別的新執行個體。Initializes a new instance of the BadImageFormatException class.

BadImageFormatException(SerializationInfo, StreamingContext) BadImageFormatException(SerializationInfo, StreamingContext) BadImageFormatException(SerializationInfo, StreamingContext) BadImageFormatException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 BadImageFormatException 類別的新執行個體。Initializes a new instance of the BadImageFormatException class with serialized data.

BadImageFormatException(String) BadImageFormatException(String) BadImageFormatException(String) BadImageFormatException(String)

使用指定的錯誤訊息,初始化 BadImageFormatException 類別的新執行個體。Initializes a new instance of the BadImageFormatException class with a specified error message.

BadImageFormatException(String, Exception) BadImageFormatException(String, Exception) BadImageFormatException(String, Exception) 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(String, String) BadImageFormatException(String, String) 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(String, String, Exception) BadImageFormatException(String, String, Exception) 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 Data Data Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
FileName FileName FileName FileName

取得造成這個例外狀況的檔案名稱。Gets the name of the file that causes this exception.

FusionLog FusionLog FusionLog FusionLog

取得描述為什麼組件 (Assembly) 載入失敗的記錄檔。Gets the log file that describes why an assembly load failed.

HelpLink HelpLink HelpLink HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

取得造成這個例外狀況的錯誤訊息和檔案名稱。Gets the error message and the name of the file that caused this exception.

Source Source Source Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(Inherited from Exception)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

使用檔案名稱、組件快取記錄檔和額外的例外狀況資訊,來設定 SerializationInfo 物件。Sets the SerializationInfo object with the file name, assembly cache log, and additional exception information.

GetType() GetType() GetType() GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() 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 SerializeObjectState SerializeObjectState SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

適用於

另請參閱