BadImageFormatException Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
A exceção é lançada quando a imagem de ficheiro de uma biblioteca de ligação dinâmica (DLL) ou de um programa executável é inválida.
public ref class BadImageFormatException : Exception
public ref class BadImageFormatException : SystemException
public class BadImageFormatException : Exception
[System.Serializable]
public class BadImageFormatException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BadImageFormatException : SystemException
public class BadImageFormatException : SystemException
type BadImageFormatException = class
inherit Exception
[<System.Serializable>]
type BadImageFormatException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type BadImageFormatException = class
inherit SystemException
type BadImageFormatException = class
inherit SystemException
Public Class BadImageFormatException
Inherits Exception
Public Class BadImageFormatException
Inherits SystemException
- Herança
- Herança
- Atributos
Observações
Esta exceção é lançada quando o formato de ficheiro de uma biblioteca de ligação dinâmica (ficheiro.dll) ou de um executável (ficheiro.exe) não cumpre o formato que o runtime da linguagem comum espera. Em particular, a exceção é lançada sob as seguintes condições:
Uma versão anterior de uma utilidade .NET, como ILDasm.exe ou installutil.exe, é usada com um assembly desenvolvido com uma versão posterior do .NET.
Para resolver esta exceção, utilize-se a versão da ferramenta que corresponde à versão do .NET que foi usada para desenvolver o assembly. Isto pode exigir modificar a
Pathvariável de ambiente ou fornecer um caminho totalmente qualificado para o executável correto.Estás a tentar carregar uma biblioteca ou executável de ligação dinâmica não gerida (como uma DLL do sistema Windows) como se fosse um assembly .NET. O exemplo seguinte ilustra isto usando o Assembly.LoadFile método para carregar 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.Para resolver esta exceção, aceda aos métodos definidos na DLL utilizando as funcionalidades fornecidas pela sua linguagem de desenvolvimento, como a instrução
Declareno Visual Basic ou o atributo DllImportAttribute com a palavra-chaveexternem C# e F#.Estás a tentar carregar uma montagem de referência num contexto diferente do contexto apenas de reflexão. Pode abordar esta questão de duas formas:
- Podes carregar o assembly de implementação em vez do assembly de referência.
- Podes carregar o conjunto de referência no contexto apenas de reflexão chamando o Assembly.ReflectionOnlyLoad método.
Uma DLL ou executável é carregada como um assembly de 64 bits, mas contém funcionalidades ou recursos de 32 bits. Por exemplo, baseia-se em interoperabilidade COM ou chama métodos numa biblioteca de ligação dinâmica de 32 bits.
Para resolver esta exceção, defina a propriedade Platform target do projeto para x86 (em vez de x64 ou AnyCPU) e recompile.
Os componentes da sua aplicação foram criados usando diferentes versões do .NET. Normalmente, esta exceção ocorre quando uma aplicação desenvolvida usando .NET Framework 2.0 SP1 ou .NET Framework 3.5 tenta carregar um assembly desenvolvido usando o .NET Framework 4 ou posterior. Pode BadImageFormatException ser reportado como um erro em tempo de compilação, ou a exceção pode ser lançada em tempo de execução. O exemplo seguinte define uma
StringLibclasse que tem um único membro,ToProperCase, e que reside numa assembleia chamada 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 ModuleO exemplo seguinte usa reflexão para carregar um conjunto chamado StringLib.dll. Se o código-fonte for compilado com um compilador .NET Framework 1.1, um método BadImageFormatException é lançado pelo método 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.Para resolver esta exceção, certifique-se de que o assembly cujo código está a ser executado e que lança a exceção, e o assembly a ser carregado, ambos têm versões compatíveis do .NET.
Os componentes da sua aplicação visam diferentes plataformas. Por exemplo, está a tentar carregar assemblies ARM numa aplicação x86. Pode usar a seguinte ferramenta de linha de comandos para determinar as plataformas-alvo de assemblies .NET individuais. A lista de ficheiros deve ser fornecida como uma lista delimitada por espaço na linha de comandos.
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 ModuleRefletir sobre ficheiros executáveis em C++ pode lançar esta exceção. Isto é muito provavelmente causado pelo compilador C++ a remover os endereços de relocação ou o . Relocar a secção do ficheiro executável. Para preservar o endereço .relocation num ficheiro executável C++, especifique /fixed:no ao ligar.
BadImageFormatException usa o HRESULT COR_E_BADIMAGEFORMAT, que tem o valor 0x8007000B.
Para obter uma lista dos valores iniciais de propriedade de uma instância de BadImageFormatException, consulte os construtores de BadImageFormatException.
Construtores
| Name | Description |
|---|---|
| BadImageFormatException() |
Inicializa uma nova instância da BadImageFormatException classe. |
| BadImageFormatException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da BadImageFormatException classe com dados serializados. |
| BadImageFormatException(String, Exception) |
Inicializa uma nova instância da BadImageFormatException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| BadImageFormatException(String, String, Exception) |
Inicializa uma nova instância da BadImageFormatException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| BadImageFormatException(String, String) |
Inicializa uma nova instância da BadImageFormatException classe com uma mensagem de erro e nome de ficheiro especificados. |
| BadImageFormatException(String) |
Inicializa uma nova instância da BadImageFormatException classe com uma mensagem de erro especificada. |
Propriedades
| Name | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção. (Herdado de Exception) |
| FileName |
Obtém o nome do ficheiro que causa esta exceção. |
| FusionLog |
Recebe o ficheiro de registo que explica porque é que uma carga de montagem falhou. |
| HelpLink |
Obtém ou define um link para o ficheiro de ajuda associado a esta exceção. (Herdado de Exception) |
| HResult |
Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Recebe a mensagem de erro e o nome do ficheiro que causou esta exceção. |
| Source |
Obtém ou define o nome do aplicativo ou o objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação string dos frames imediatos na stack de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que lança a exceção atual. (Herdado de Exception) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Define o SerializationInfo objeto com o nome do ficheiro, o registo de cache de montagem e informações adicionais de exceção. |
| GetType() |
Obtém o tipo de execução da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve o nome totalmente qualificado desta exceção e possivelmente a mensagem de erro, o nome da exceção interna e o rastreio da pilha. |
evento
| Name | Description |
|---|---|
| SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |