BadImageFormatException Kelas
Definisi
Penting
Beberapa informasi terkait produk prarilis yang dapat diubah secara signifikan sebelum dirilis. Microsoft tidak memberikan jaminan, tersirat maupun tersurat, sehubungan dengan informasi yang diberikan di sini.
Pengecualian yang dilemparkan ketika gambar file pustaka tautan dinamis (DLL) atau program yang dapat dieksekusi tidak valid.
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
- Warisan
- Warisan
- Atribut
Keterangan
Pengecualian ini dilemparkan ketika format file pustaka tautan dinamis (file.dll) atau file yang dapat dieksekusi (.exe) tidak sesuai dengan format yang diharapkan runtime bahasa umum. Secara khusus, pengecualian dilemparkan dalam kondisi berikut:
Versi utilitas .NET yang lebih lama, seperti ILDasm.exe atau installutil.exe, digunakan dengan rakitan yang dikembangkan dengan versi .NET yang lebih baru.
Untuk mengatasi pengecualian ini, gunakan versi alat yang sesuai dengan versi .NET yang digunakan untuk mengembangkan perakitan. Ini mungkin memerlukan modifikasi
Pathvariabel lingkungan atau menyediakan jalur yang sepenuhnya memenuhi syarat ke yang dapat dieksekusi yang benar.Anda mencoba memuat pustaka tautan dinamis yang tidak dikelola atau dapat dieksekusi (seperti DLL sistem Windows) seolah-olah itu adalah rakitan .NET. Contoh berikut mengilustrasikan ini dengan menggunakan Assembly.LoadFile metode untuk memuat 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.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.Untuk mengatasi pengecualian ini, akses metode yang ditentukan dalam DLL dengan menggunakan fitur yang disediakan oleh bahasa pengembangan Anda, seperti pernyataan
Declaredalam atribut Visual Basic atau DllImportAttribute dengan kata kunciexterndi C# dan F#.Anda mencoba memuat rakitan referensi dalam konteks selain konteks khusus refleksi. Anda dapat mengatasi masalah ini dengan salah satu dari dua cara:
- Anda dapat memuat rakitan implementasi daripada rakitan referensi.
- Anda dapat memuat rakitan referensi dalam konteks khusus pantulan dengan memanggil Assembly.ReflectionOnlyLoad metode .
DLL atau executable dimuat sebagai rakitan 64-bit, tetapi berisi fitur atau sumber daya 32-bit. Misalnya, ini bergantung pada interop COM atau memanggil metode di pustaka tautan dinamis 32-bit.
Untuk mengatasi pengecualian ini, atur properti target Platform proyek ke x86 (bukan x64 atau AnyCPU) dan kompilasi ulang.
Komponen aplikasi Anda dibuat menggunakan versi .NET yang berbeda. Biasanya, pengecualian ini terjadi ketika aplikasi yang dikembangkan menggunakan .NET Framework 2.0 SP1 atau .NET Framework 3.5 mencoba memuat rakitan yang dikembangkan menggunakan .NET Framework 4 atau yang lebih baru. BadImageFormatException mungkin dilaporkan sebagai kesalahan waktu kompilasi, atau pengecualian dapat dilemparkan pada waktu proses. Contoh berikut mendefinisikan
StringLibkelas yang memiliki satu anggota,ToProperCase, dan yang berada di rakitan bernama 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 ModuleContoh berikut menggunakan pantulan untuk memuat rakitan bernama StringLib.dll. Jika kode sumber dikompilasi dengan pengkompilasi .NET Framework 1.1, BadImageFormatException dilemparkan oleh metode 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.Untuk mengatasi pengecualian ini, pastikan bahwa rakitan yang kodenya dijalankan dan yang melemparkan pengecualian, dan rakitan yang akan dimuat, kedua versi .NET yang kompatibel target.
Komponen aplikasi Anda menargetkan platform yang berbeda. Misalnya, Anda mencoba memuat rakitan ARM dalam aplikasi x86. Anda dapat menggunakan utilitas baris perintah berikut untuk menentukan platform target rakitan .NET individual. Daftar file harus disediakan sebagai daftar yang dibatasi spasi di baris perintah.
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 ModuleMencerminkan file yang dapat dieksekusi C++ mungkin melemparkan pengecualian ini. Ini kemungkinan besar disebabkan oleh kompilator C++ yang menghapus alamat relokasi atau . Relokasi bagian dari file yang dapat dieksekusi. Untuk mempertahankan alamat .relokasi dalam file C++ yang dapat dieksekusi, tentukan /fixed:no saat menautkan.
BadImageFormatException menggunakan HRESULT COR_E_BADIMAGEFORMAT, yang memiliki nilai 0x8007000B.
Untuk daftar nilai properti awal untuk instance BadImageFormatException, silakan lihat konstruktor BadImageFormatException.
Konstruktor
| Nama | Deskripsi |
|---|---|
| BadImageFormatException() |
Menginisialisasi instans baru dari kelas BadImageFormatException. |
| BadImageFormatException(SerializationInfo, StreamingContext) |
Kedaluwarsa.
Menginisialisasi instans BadImageFormatException baru kelas dengan data berseri. |
| BadImageFormatException(String, Exception) |
Menginisialisasi instans BadImageFormatException baru kelas dengan pesan kesalahan tertentu dan referensi ke pengecualian dalam yang merupakan penyebab pengecualian ini. |
| BadImageFormatException(String, String, Exception) |
Menginisialisasi instans BadImageFormatException baru kelas dengan pesan kesalahan tertentu dan referensi ke pengecualian dalam yang merupakan penyebab pengecualian ini. |
| BadImageFormatException(String, String) |
Menginisialisasi instans BadImageFormatException baru kelas dengan pesan kesalahan dan nama file tertentu. |
| BadImageFormatException(String) |
Menginisialisasi instans baru kelas BadImageFormatException dengan pesan kesalahan tertentu. |
Properti
| Nama | Deskripsi |
|---|---|
| Data |
Mendapatkan kumpulan pasangan kunci/nilai yang memberikan informasi tambahan yang ditentukan pengguna tentang pengecualian. (Diperoleh dari Exception) |
| FileName |
Mendapatkan nama file yang menyebabkan pengecualian ini. |
| FusionLog |
Mendapatkan file log yang menjelaskan mengapa pemuatan rakitan gagal. |
| HelpLink |
Mendapatkan atau mengatur tautan ke file bantuan yang terkait dengan pengecualian ini. (Diperoleh dari Exception) |
| HResult |
Mendapatkan atau mengatur HRESULT, nilai numerik berkode yang ditetapkan ke pengecualian tertentu. (Diperoleh dari Exception) |
| InnerException |
Mendapatkan instans Exception yang menyebabkan pengecualian saat ini. (Diperoleh dari Exception) |
| Message |
Mendapatkan pesan kesalahan dan nama file yang menyebabkan pengecualian ini. |
| Source |
Mendapatkan atau mengatur nama aplikasi atau objek yang menyebabkan kesalahan. (Diperoleh dari Exception) |
| StackTrace |
Mendapatkan representasi string dari bingkai langsung pada tumpukan panggilan. (Diperoleh dari Exception) |
| TargetSite |
Mendapatkan metode yang melemparkan pengecualian saat ini. (Diperoleh dari Exception) |
Metode
| Nama | Deskripsi |
|---|---|
| Equals(Object) |
Menentukan apakah objek yang ditentukan sama dengan objek saat ini. (Diperoleh dari Object) |
| GetBaseException() |
Ketika ditimpa di kelas turunan, mengembalikan Exception yang merupakan akar penyebab dari satu atau beberapa pengecualian berikutnya. (Diperoleh dari Exception) |
| GetHashCode() |
Berfungsi sebagai fungsi hash default. (Diperoleh dari Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Kedaluwarsa.
SerializationInfo Mengatur objek dengan nama file, log cache rakitan, dan informasi pengecualian tambahan. |
| GetType() |
Mendapatkan jenis runtime instans saat ini. (Diperoleh dari Exception) |
| MemberwiseClone() |
Membuat salinan dangkal dari Objectsaat ini. (Diperoleh dari Object) |
| ToString() |
Mengembalikan nama pengecualian ini yang sepenuhnya memenuhi syarat dan mungkin pesan kesalahan, nama pengecualian dalam, dan jejak tumpukan. |
Acara
| Nama | Deskripsi |
|---|---|
| SerializeObjectState |
Kedaluwarsa.
Terjadi ketika pengecualian diserialisasikan untuk membuat objek status pengecualian yang berisi data berseri tentang pengecualian. (Diperoleh dari Exception) |