BadImageFormatException Classe

Definizione

Eccezione generata quando l'immagine del file di una libreria di collegamento dinamico (DLL, Dynamic Link Library) o di un programma eseguibile non è valida.

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
Ereditarietà
BadImageFormatException
Ereditarietà
BadImageFormatException
Attributi

Commenti

Questa eccezione viene generata quando il formato di file di una libreria di collegamento dinamica (.dll file) o un file eseguibile (.exe file) non è conforme al formato previsto da Common Language Runtime. In particolare, l'eccezione viene generata in base alle condizioni seguenti:

  • Una versione precedente di un'utilità .NET, ad esempio ILDasm.exe o installutil.exe, viene usata con un assembly sviluppato con una versione successiva di .NET.

    Per risolvere questa eccezione, usare la versione dello strumento che corrisponde alla versione di .NET usata per sviluppare l'assembly. Ciò può richiedere la modifica della Path variabile di ambiente o fornire un percorso completo al file eseguibile corretto.

  • Si sta tentando di caricare una libreria di collegamento dinamica non gestita o eseguibile (ad esempio una DLL di sistema windows) come se fosse un assembly .NET. L'esempio seguente illustra questa operazione usando il Assembly.LoadFile metodo per caricare 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.
    

    Per risolvere questa eccezione, accedere ai metodi definiti nella DLL usando le funzionalità fornite dal linguaggio di sviluppo, ad esempio l'istruzione in Visual Basic o l'attributo DeclareDllImportAttribute con la extern parola chiave in C# e F#.

  • Si sta tentando di caricare un assembly di riferimento in un contesto diverso dal contesto di sola reflection. È possibile risolvere questo problema in uno dei due modi seguenti:

    • È possibile caricare l'assembly di implementazione anziché l'assembly di riferimento.
    • È possibile caricare l'assembly di riferimento nel contesto di sola reflection chiamando il Assembly.ReflectionOnlyLoad metodo .
  • Una DLL o un eseguibile viene caricato come assembly a 64 bit, ma contiene funzionalità o risorse a 32 bit. Ad esempio, si basa su metodi di interoperabilità o chiamate COM in una libreria di collegamento dinamica a 32 bit.

    Per risolvere questa eccezione, impostare la proprietà di destinazione Della piattaforma del progetto su x86 (anziché x64 o AnyCPU) e ricompilare.

  • I componenti dell'applicazione sono stati creati usando versioni diverse di .NET. In genere, questa eccezione si verifica quando un'applicazione o un componente sviluppato usando .NET Framework 1.0 o .NET Framework 1.1 tenta di caricare un assembly sviluppato usando .NET Framework 2.0 SP1 o versione successiva oppure quando un'applicazione sviluppata usando .NET Framework 2.0 SP1 o .NET Framework 3.5 tenta di caricare un assembly sviluppato usando .NET Framework 4 o versione successiva. L'oggetto BadImageFormatException può essere segnalato come errore in fase di compilazione oppure l'eccezione può essere generata in fase di esecuzione. Nell'esempio seguente viene definita una StringLib classe con un singolo membro, ToProperCasee che risiede in un assembly denominato 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 Module
    

    Nell'esempio seguente viene usata la reflection per caricare un assembly denominato StringLib.dll. Se il codice sorgente viene compilato con un compilatore .NET Framework 1.1, viene BadImageFormatException generato dal Assembly.LoadFrom metodo .

    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.
    

    Per risolvere questa eccezione, assicurarsi che l'assembly il cui codice sia in esecuzione e che generi l'eccezione e che l'assembly venga caricato, entrambe le versioni compatibili con .NET.

  • I componenti dell'applicazione sono destinati a piattaforme diverse. Ad esempio, si sta tentando di caricare assembly ARM in un'applicazione x86. È possibile usare l'utilità della riga di comando seguente per determinare le piattaforme di destinazione di singoli assembly .NET. L'elenco dei file deve essere fornito come elenco delimitato da spazio nella riga di 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 Module
    
  • Questa eccezione può essere generata dalla reflection su file eseguibili C++. Nella maggior parte dei casi la causa è la rimozione da parte del compilatore C++ degli indirizzi di rilocazione oppure della sezione .Reloc nel file eseguibile. Per mantenere l'indirizzo di rilocazione in un file eseguibile C++, specificare /fixed:no durante il collegamento.

BadImageFormatException usa HRESULT COR_E_BADIMAGEFORMAT, che ha il valore 0x8007000B.

Per un elenco di valori di proprietà iniziali per un'istanza di BadImageFormatException, vedere il BadImageFormatException costruttori.

Costruttori

BadImageFormatException()

Inizializza una nuova istanza della classe BadImageFormatException.

BadImageFormatException(SerializationInfo, StreamingContext)

Inizializza una nuova istanza della classe BadImageFormatException con dati serializzati.

BadImageFormatException(String)

Inizializza una nuova istanza della classe BadImageFormatException con un messaggio di errore specificato.

BadImageFormatException(String, Exception)

Inizializza una nuova istanza della classe BadImageFormatException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.

BadImageFormatException(String, String)

Inizializza una nuova istanza della classe BadImageFormatException con il messaggio di errore e il nome del file specificati.

BadImageFormatException(String, String, Exception)

Inizializza una nuova istanza della classe BadImageFormatException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.

Proprietà

Data

Ottiene una raccolta di coppie chiave/valore che forniscono informazioni definite dall'utente aggiuntive sull'eccezione.

(Ereditato da Exception)
FileName

Ottiene il nome del file che ha causato questa eccezione.

FusionLog

Ottiene il file di log che descrive il motivo dell'errore nel caricamento di un assembly.

HelpLink

Ottiene o imposta un collegamento al file della Guida associato all'eccezione.

(Ereditato da Exception)
HResult

Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato a un'eccezione specifica.

(Ereditato da Exception)
InnerException

Ottiene l'istanza di Exception che ha causato l'eccezione corrente.

(Ereditato da Exception)
Message

Ottiene il messaggio di errore e il nome del file che ha causato questa eccezione.

Source

Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.

(Ereditato da Exception)
StackTrace

Ottiene una rappresentazione di stringa dei frame immediati nello stack di chiamate.

(Ereditato da Exception)
TargetSite

Ottiene il metodo che genera l'eccezione corrente.

(Ereditato da Exception)

Metodi

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetBaseException()

Quando ne viene eseguito l'override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.

(Ereditato da Exception)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetObjectData(SerializationInfo, StreamingContext)

Imposta l'oggetto SerializationInfo con il nome del file, il log della cache dell'assembly e le informazioni aggiuntive sull'eccezione.

GetObjectData(SerializationInfo, StreamingContext)

Quando ne viene eseguito l'override in una classe derivata, imposta il controllo SerializationInfo con le informazioni sull'eccezione.

(Ereditato da Exception)
GetType()

Ottiene il tipo di runtime dell'istanza corrente.

(Ereditato da Exception)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Restituisce il nome completo di questa eccezione ed eventualmente il messaggio di errore, il nome dell'eccezione interna e l'analisi dello stack.

Eventi

SerializeObjectState
Obsoleti.

Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.

(Ereditato da Exception)

Si applica a

Vedi anche