BadImageFormatException Classe
Definição
A exceção que é gerada quando a imagem do arquivo de uma DLL (biblioteca de vínculo dinâmico) ou um programa executável é inválida.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
- Herança
- Atributos
Comentários
Essa exceção é gerada quando o formato de arquivo de uma biblioteca de vínculo dinâmico (arquivo. dll) ou um executável (arquivo. exe) não está de acordo com o formato esperado pelo 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. Em particular, a exceção é lançada sob as seguintes condições:In particular, the exception is thrown under the following conditions:
Uma versão anterior de um utilitário de .NET Framework, como ILDasm. exe ou InstallUtil. exe, é usada com um assembly que foi desenvolvido com uma versão posterior do .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.
Para resolver essa exceção, use a versão da ferramenta que corresponde à versão do .NET Framework que foi usada para desenvolver o assembly.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. Isso pode exigir a modificação
Path
da variável de ambiente ou o fornecimento de um caminho totalmente qualificado para o executável correto.This may require modifying thePath
environment variable or providing a fully qualified path to the correct executable.Você está tentando carregar uma biblioteca de vínculo dinâmico não gerenciada ou um executável (como uma DLL de sistema do Windows) como se fosse um assembly .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. O exemplo a seguir ilustra isso usando o Assembly.LoadFile método para carregar 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.
Para resolver essa exceção, acesse os métodos definidos na DLL usando os recursos fornecidos pela sua
Declare
linguagem de desenvolvimento, como a instrução em Visual Basic ou o DllImportAttribute atributo com aextern
palavra-chave C#em.To address this exception, access the methods defined in the DLL by using the features provided by your development language, such as theDeclare
statement in Visual Basic or the DllImportAttribute attribute with theextern
keyword in C#.Você está tentando carregar um assembly de referência em um contexto diferente do contexto somente de reflexão.You are trying to load a reference assembly in a context other than the reflection-only context. Você pode resolver esse problema de uma das duas maneiras:You can address this issue in either of two ways:
- Você pode carregar o assembly de implementação em vez do assembly de referência.You can load the implementation assembly rather than the reference assembly.
- Você pode carregar o assembly de referência no contexto somente de reflexão chamando o Assembly.ReflectionOnlyLoad método.You can load the reference assembly in the reflection-only context by calling the Assembly.ReflectionOnlyLoad method.
Uma DLL ou um executável é carregado como um assembly de 64 bits, mas contém recursos ou recursos de 32 bits.A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources. Por exemplo, ele se baseia em interoperabilidade COM ou chama métodos em uma biblioteca de vínculo dinâmico de 32 bits.For example, it relies on COM interop or calls methods in a 32-bit dynamic link library.
Para resolver essa exceção, defina a propriedade de destino da plataforma do projeto como x86 (em vez de x64 ou anycpu) e recompile.To address this exception, set the project's Platform target property to x86 (instead of x64 or AnyCPU) and recompile.
Os componentes do aplicativo foram criados usando diferentes versões do .NET Framework.Your application's components were created using different versions of the .NET Framework. Normalmente, essa exceção ocorre quando um aplicativo ou componente que foi desenvolvido usando o .NET Framework 1.0.NET Framework 1.0 ou o .NET Framework 1.1.NET Framework 1.1 tenta carregar um assembly que foi desenvolvido usando o .NET Framework 2.0 SP1.NET Framework 2.0 SP1 ou posterior, ou quando um aplicativo que foi desenvolvido usando o ou tenta carregar um assembly que foi desenvolvido usando o .NET Framework 4.NET Framework 4 ou posterior. .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. O BadImageFormatException pode ser relatado como um erro de tempo de compilação ou a exceção pode ser lançada em tempo de execução.The BadImageFormatException may be reported as a compile-time error, or the exception may be thrown at run time. O exemplo a seguir define
StringLib
uma classe que tem um único membroToProperCase
, e que reside em um assembly chamado StringLib. dll.The following example defines aStringLib
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
O exemplo a seguir usa a reflexão para carregar um assembly chamado StringLib. dll.The following example uses reflection to load an assembly named StringLib.dll. Se o código-fonte for compilado com .NET Framework 1.1.NET Framework 1.1 um compilador, BadImageFormatException um será gerado pelo Assembly.LoadFrom método.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.
Para resolver essa exceção, certifique-se de que o assembly cujo código está sendo executado e que gera a exceção, e que o assembly seja carregado ambas as versões compatíveis de destino do .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.
Os componentes de seu aplicativo têm como destino diferentes plataformas.The components of your application target different platforms. Por exemplo, você está tentando carregar assemblies de ARM em um aplicativo x86.For example, you are trying to load ARM assemblies in an x86 application. Você pode usar o seguinte utilitário de linha de comando para determinar as plataformas de destino de assemblies de .NET Framework individuais.You can use the following command-line utility to determine the target platforms of individual .NET Framework assemblies. A lista de arquivos deve ser fornecida como uma lista delimitada por espaço na linha de comando.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
Refletir em arquivos executáveis C++ pode gerar essa exceção.Reflecting on C++ executable files may throw this exception. Isso é muito provavelmente causado pelo compilador C++ que retira os endereços de realocação ou a seção .Reloc do arquivo executável.This is most likely caused by the C++ compiler stripping the relocation addresses or the .Reloc section from the executable file. Para preservar o endereço. realocação em C++ um arquivo executável, especifique/fixed: não ao vincular.To preserve the .relocation address in a C++ executable file, specify /fixed:no when linking.
BadImageFormatExceptionusa o HRESULT COR_E_BADIMAGEFORMAT, que tem o valor 0x8007000B.BadImageFormatException uses the HRESULT COR_E_BADIMAGEFORMAT, which has the value 0x8007000B.
Para obter uma lista de valores de propriedade inicial para uma instância do BadImageFormatException, consulte o BadImageFormatException construtores.For a list of initial property values for an instance of BadImageFormatException, see the BadImageFormatException constructors.
Construtores
BadImageFormatException() |
Inicializa uma nova instância da classe BadImageFormatException.Initializes a new instance of the BadImageFormatException class. |
BadImageFormatException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da classe BadImageFormatException com dados serializados.Initializes a new instance of the BadImageFormatException class with serialized data. |
BadImageFormatException(String) |
Inicializa uma nova instância da classe BadImageFormatException com uma mensagem de erro especificada.Initializes a new instance of the BadImageFormatException class with a specified error message. |
BadImageFormatException(String, Exception) |
Inicializa uma nova instância da classe BadImageFormatException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa da exceção.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) |
Inicializa uma nova instância da classe BadImageFormatException com uma mensagem de erro e um nome de arquivo especificados.Initializes a new instance of the BadImageFormatException class with a specified error message and file name. |
BadImageFormatException(String, String, Exception) |
Inicializa uma nova instância da classe BadImageFormatException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa da exceção.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. |
Propriedades
Data |
Obtém uma coleção de pares de chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção.Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Herdado de Exception) |
FileName |
Obtém o nome do parâmetro que causa essa exceção.Gets the name of the file that causes this exception. |
FusionLog |
Obtém o arquivo de log que descreve por que um carregamento de assembly falhou.Gets the log file that describes why an assembly load failed. |
HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção.Gets or sets a link to the help file associated with this exception. (Herdado de Exception) |
HResult |
Obtém ou define HRESULT, um valor numérico codificado que é atribuído a uma exceção específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Herdado de Exception) |
InnerException |
Obtém a instância Exception que causou a exceção atual.Gets the Exception instance that caused the current exception. (Herdado de Exception) |
Message |
Obtém a mensagem de erro e o nome do arquivo que provocou essa exceção.Gets the error message and the name of the file that caused this exception. |
Source |
Obtém ou define o nome do aplicativo ou objeto que causa o erro.Gets or sets the name of the application or the object that causes the error. (Herdado de Exception) |
StackTrace |
Obtém uma representação de cadeia de caracteres de quadros imediatos na pilha de chamadas.Gets a string representation of the immediate frames on the call stack. (Herdado de Exception) |
TargetSite |
Obtém o método que gerou a exceção atual.Gets the method that throws the current exception. (Herdado de Exception) |
Métodos
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception que é a causa raiz de uma ou mais exceções subsequentes.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Herdado de Exception) |
GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Define o objeto SerializationInfo com o nome do arquivo, log do cache de assemblies e informações de exceção adicionais.Sets the SerializationInfo object with the file name, assembly cache log, and additional exception information. |
GetType() |
Obtém o tipo de tempo de execução da instância atual.Gets the runtime type of the current instance. (Herdado de Exception) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (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.Returns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace. |
Eventos
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.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Herdado de Exception) |