BadImageFormatException Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
A exceção gerada quando a imagem de arquivo de uma DLL (biblioteca de link dinâmico) 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
Comentários
Essa exceção é gerada quando o formato de arquivo de uma biblioteca de link dinâmico (.dll arquivo) ou um executável (.exe arquivo) não está em conformidade com o formato esperado pelo common language runtime. Em particular, a exceção é lançada sob as seguintes condições:
Uma versão anterior de um utilitário .NET, como ILDasm.exe ou installutil.exe, é usada com um assembly que foi desenvolvido com uma versão posterior do .NET.
Para resolver essa exceção, use a versão da ferramenta que corresponde à versão de .NET que foi usada para desenvolver o assembly. Isso pode exigir a modificação da variável de
Pathambiente ou o fornecimento de um caminho totalmente qualificado para o executável correto.Você está tentando carregar uma biblioteca de link dinâmico não gerenciada ou executável (como uma DLL do sistema Windows) como se fosse um assembly .NET. O exemplo a seguir ilustra isso 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 essa exceção, acesse os métodos definidos na DLL usando os recursos fornecidos pela linguagem de desenvolvimento, como a instrução
Declareem Visual Basic ou o atributo DllImportAttribute com a palavra-chaveexternem C# e F#.Você está tentando carregar um assembly de referência em um contexto diferente do contexto somente reflexão. Você pode resolver esse problema de duas maneiras:
- Você pode carregar o assembly de implementação em vez do assembly de referência.
- Você pode carregar o assembly de referência no contexto somente reflexão chamando o Assembly.ReflectionOnlyLoad método.
Uma DLL ou executável é carregada como um assembly de 64 bits, mas contém recursos ou recursos de 32 bits. Por exemplo, ele depende da interoperabilidade COM ou chama métodos em uma biblioteca de vínculo dinâmico de 32 bits.
Para resolver essa exceção, defina a propriedade de destino plataforma do projeto como x86 (em vez de x64 ou AnyCPU) e recompile.
Os componentes do aplicativo foram criados usando diferentes versões de .NET. Normalmente, essa exceção ocorre quando um aplicativo que foi desenvolvido usando .NET Framework 2.0 SP1 ou .NET Framework 3.5 tenta carregar um assembly que foi desenvolvido usando .NET Framework 4 ou posterior. Pode BadImageFormatException ser relatado como um erro de tempo de compilação ou a exceção pode ser gerada em tempo de execução. O exemplo a seguir define uma
StringLibclasse que tem um único membroToProperCasee que reside em um assembly chamado 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 a seguir usa reflexão para carregar um assembly chamado StringLib.dll. Se o código-fonte for compilado com um compilador do .NET Framework 1.1, um BadImageFormatException será gerado 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 essa exceção, verifique se o assembly cujo código está sendo executado e que gera a exceção e o assembly a ser carregado, ambas as versões compatíveis de destino de .NET.
Os componentes do aplicativo têm como destino diferentes plataformas. Por exemplo, você está tentando carregar assemblies ARM em um aplicativo x86. Você pode usar o utilitário de linha de comando a seguir para determinar as plataformas de destino de assemblies .NET individuais. A lista de arquivos deve ser fornecida como uma lista delimitada por espaço na linha de comando.
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 arquivos executáveis C++ pode gerar essa exceção. Isso provavelmente é causado pelo compilador C++ despojando os endereços de realocação ou o . Relocar a seção do arquivo executável. Para preservar o endereço .relocation em um arquivo executável C++, especifique /fixed:no ao vincular.
BadImageFormatException usa o HRESULT COR_E_BADIMAGEFORMAT, que tem o valor 0x8007000B.
Para obter uma lista de valores de propriedade iniciais de uma instância de BadImageFormatException, consulte os construtores de BadImageFormatException.
Construtores
| Nome | Description |
|---|---|
| BadImageFormatException() |
Inicializa uma nova instância da classe BadImageFormatException. |
| 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 um nome de arquivo especificados. |
| BadImageFormatException(String) |
Inicializa uma nova instância da classe BadImageFormatException com uma mensagem de erro especificada. |
Propriedades
| Nome | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção. (Herdado de Exception) |
| FileName |
Obtém o nome do arquivo que causa essa exceção. |
| FusionLog |
Obtém o arquivo de log que descreve por que uma carga de assembly falhou. |
| HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção. (Herdado de Exception) |
| HResult |
Obtém 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 |
Obtém a mensagem de erro e o nome do arquivo que causou essa exceção. |
| Source |
Obtém ou define o nome do aplicativo ou do objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação de cadeia de caracteres dos quadros imediatos na pilha de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que gera a exceção atual. (Herdado de Exception) |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Define o SerializationInfo objeto com o nome do arquivo, o log de cache do assembly e informações adicionais de exceção. |
| GetType() |
Obtém o tipo de runtime da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Retorna o nome totalmente qualificado dessa exceção e, possivelmente, a mensagem de erro, o nome da exceção interna e o rastreamento de pilha. |
Eventos
| Nome | 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) |