BadImageFormatException Sınıf

Tanım

Dinamik bağlantı kitaplığının (DLL) veya yürütülebilir bir programın dosya görüntüsü geçersiz olduğunda oluşan özel durum.

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
Devralma
BadImageFormatException
Devralma
BadImageFormatException
Öznitelikler

Açıklamalar

Bu özel durum, dinamik bağlantı kitaplığının (.dll dosyası) veya yürütülebilir dosyanın (.exe dosyası) dosya biçimi ortak dil çalışma zamanının beklediği biçime uymadığında oluşur. Özellikle, özel durum aşağıdaki koşullar altında oluşturulur:

  • .NET yardımcı programının ILDasm.exe veya installutil.exegibi önceki bir sürümü, .NET'nin daha sonraki bir sürümüyle geliştirilmiş bir derlemeyle birlikte kullanılır.

    Bu özel durumu gidermek için, aracın derlemeyi geliştirmek için kullanılan .NET sürümüne karşılık gelen sürümünü kullanın. Bunun için ortam değişkeninin Path değiştirilmesi veya doğru yürütülebilir dosyanın tam yolunun sağlanması gerekebilir.

  • Yönetilmeyen bir dinamik bağlantı kitaplığını veya yürütülebilir dosyayı (Windows sistem DLL'si gibi) .NET bir derlemeymiş gibi yüklemeye çalışıyorsunuz. Aşağıdaki örnek, Kernel32.dllyüklemek için yöntemini kullanarak Assembly.LoadFile bunu gösterir.

    // 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.
    

    Bu özel durumu gidermek için, Visual Basic içindeki Declare deyimi veya C# ve F# dilinde DllImportAttribute anahtar sözcüğüne sahip extern özniteliği gibi geliştirme dilinizin sağladığı özellikleri kullanarak DLL'de tanımlanan yöntemlere erişin.

  • Başvuru derlemesini yalnızca yansıma bağlamı dışında bir bağlamda yüklemeye çalışıyorsunuz. Bu sorunu iki yoldan biriyle çözebilirsiniz:

    • Başvuru derlemesi yerine uygulama derlemesini yükleyebilirsiniz.
    • yöntemini çağırarak Assembly.ReflectionOnlyLoad başvuru derlemesini yalnızca yansıma bağlamında yükleyebilirsiniz.
  • DLL veya yürütülebilir dosya 64 bit derleme olarak yüklenir, ancak 32 bit özellikler veya kaynaklar içerir. Örneğin, COM birlikte çalışmalarına dayanır veya 32 bit dinamik bağlantı kitaplığındaki yöntemleri çağırır.

    Bu özel durumu gidermek için projenin Platform hedef özelliğini x86 (x64 veya AnyCPU yerine) olarak ayarlayın ve yeniden derleyin.

  • Uygulamanızın bileşenleri farklı .NET sürümleri kullanılarak oluşturuldu. Bu özel durum genellikle, .NET Framework 2.0 SP1 veya .NET Framework 3.5 kullanılarak geliştirilmiş bir uygulama .NET Framework 4 veya üzeri kullanılarak geliştirilmiş bir derlemeyi yüklemeye çalıştığında oluşur. BadImageFormatException derleme zamanı hatası olarak bildirilebilir veya çalışma zamanında özel durum oluşturulabilir. Aşağıdaki örnek, StringLibtek bir üyesi olan ve StringLib.dlladlı bir derlemede bulunan bir sınıfı tanımlarToProperCase.

    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
    

    Aşağıdaki örnek, StringLib.dlladlı bir derlemeyi yüklemek için yansımayı kullanır. Kaynak kodu bir .NET Framework 1.1 derleyicisi ile derlenmişse, BadImageFormatException yöntemi tarafından bir Assembly.LoadFrom oluşturulur.

    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.
    

    Bu özel durumu gidermek için kodu yürütülen ve özel durum oluşturan derlemenin ve yüklenecek derlemenin her iki .NET uyumlu sürümlerini de hedeflediğinden emin olun.

  • Uygulamanızın bileşenleri farklı platformları hedefler. Örneğin, bir x86 uygulamasında ARM derlemelerini yüklemeye çalışıyorsunuz. Tek tek .NET derlemelerinin hedef platformlarını belirlemek için aşağıdaki komut satırı yardımcı programını kullanabilirsiniz. Dosya listesi, komut satırında boşlukla ayrılmış bir liste olarak sağlanmalıdır.

    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
    
  • C++ yürütülebilir dosyalarına yansıtılması bu özel duruma neden olabilir. Bunun nedeni büyük olasılıkla C++ derleyicisinin yeniden konumlandırma adreslerini veya öğesini kaldırmasıdır. Bölümü yürütülebilir dosyadan yeniden konumlandırın. C++ yürütülebilir dosyasında .relocation adresini korumak için bağlantı oluştururken /fixed:no belirtin.

BadImageFormatException , 0x8007000B değerine sahip HRESULT COR_E_BADIMAGEFORMATkullanır.

BadImageFormatExceptionörneğinin ilk özellik değerlerinin listesi için bkz. BadImageFormatException oluşturucuları.

Oluşturucular

Name Description
BadImageFormatException()

BadImageFormatException sınıfının yeni bir örneğini başlatır.

BadImageFormatException(SerializationInfo, StreamingContext)
Geçersiz.

Serileştirilmiş verilerle BadImageFormatException sınıfının yeni bir örneğini başlatır.

BadImageFormatException(String, Exception)

Belirtilen bir hata iletisi ve bu özel durumun nedeni olan iç özel duruma başvuru ile BadImageFormatException sınıfının yeni bir örneğini başlatır.

BadImageFormatException(String, String, Exception)

Belirtilen bir hata iletisi ve bu özel durumun nedeni olan iç özel duruma başvuru ile BadImageFormatException sınıfının yeni bir örneğini başlatır.

BadImageFormatException(String, String)

Belirtilen hata iletisi ve dosya adıyla sınıfın BadImageFormatException yeni bir örneğini başlatır.

BadImageFormatException(String)

Belirtilen bir hata iletisiyle sınıfının yeni bir örneğini BadImageFormatException başlatır.

Özellikler

Name Description
Data

Özel durum hakkında kullanıcı tanımlı ek bilgiler sağlayan anahtar/değer çiftleri koleksiyonunu alır.

(Devralındığı yer: Exception)
FileName

Bu özel duruma neden olan dosyanın adını alır.

FusionLog

Derleme yükünün neden başarısız olduğunu açıklayan günlük dosyasını alır.

HelpLink

Bu özel durumla ilişkili yardım dosyasının bağlantısını alır veya ayarlar.

(Devralındığı yer: Exception)
HResult

Belirli bir özel duruma atanan kodlanmış sayısal bir değer olan HRESULT değerini alır veya ayarlar.

(Devralındığı yer: Exception)
InnerException

Geçerli özel duruma neden olan Exception örneğini alır.

(Devralındığı yer: Exception)
Message

Hata iletisini ve bu özel duruma neden olan dosyanın adını alır.

Source

Hataya neden olan uygulamanın veya nesnenin adını alır veya ayarlar.

(Devralındığı yer: Exception)
StackTrace

Çağrı yığınındaki anlık çerçevelerin dize gösterimini alır.

(Devralındığı yer: Exception)
TargetSite

Geçerli özel durumu oluşturan yöntemini alır.

(Devralındığı yer: Exception)

Yöntemler

Name Description
Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.

(Devralındığı yer: Object)
GetBaseException()

Türetilmiş bir sınıfta geçersiz kılındığında, sonraki bir veya daha fazla özel durumun kök nedeni olan Exception döndürür.

(Devralındığı yer: Exception)
GetHashCode()

Varsayılan karma işlevi işlevi görür.

(Devralındığı yer: Object)
GetObjectData(SerializationInfo, StreamingContext)
Geçersiz.

SerializationInfo Nesneyi dosya adı, derleme önbellek günlüğü ve ek özel durum bilgileriyle ayarlar.

GetType()

Geçerli örneğin çalışma zamanı türünü alır.

(Devralındığı yer: Exception)
MemberwiseClone()

Geçerli Objectbasit bir kopyasını oluşturur.

(Devralındığı yer: Object)
ToString()

Bu özel durumun tam adını ve büyük olasılıkla hata iletisini, iç özel durumun adını ve yığın izlemesini döndürür.

Ekinlikler

Name Description
SerializeObjectState
Geçersiz.

Özel durum hakkında serileştirilmiş veriler içeren bir özel durum durumu nesnesi oluşturmak için bir özel durum seri hale getirildiğinde gerçekleşir.

(Devralındığı yer: Exception)

Şunlara uygulanır

Ayrıca bkz.