BadImageFormatException 클래스

정의

DLL(동적 연결 라이브러리)의 파일 이미지 또는 실행 가능한 프로그램이 유효하지 않을 때 throw되는 예외입니다.

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
상속
BadImageFormatException
상속
BadImageFormatException
특성

설명

이 예외는 동적 링크 라이브러리(.dll 파일) 또는 실행 파일(.exe 파일)의 파일 형식이 공용 언어 런타임에서 예상하는 형식을 준수하지 않을 때 throw됩니다. 특히 예외는 다음 조건에서 throw됩니다.

  • ILDasm.exe 또는 installutil.exe 같은 이전 버전의 .NET 유틸리티는 이후 버전의 .NET으로 개발된 어셈블리와 함께 사용됩니다.

    이 예외를 해결하려면 어셈블리를 개발하는 데 사용된 .NET 버전에 해당하는 도구 버전을 사용합니다. 이를 위해서는 환경 변수를 Path 수정하거나 올바른 실행 파일에 정규화된 경로를 제공해야 할 수 있습니다.

  • 관리되지 않는 동적 링크 라이브러리 또는 실행 파일(예: Windows 시스템 DLL)을 .NET 어셈블리인 것처럼 로드하려고 합니다. 다음 예제에서는 메서드를 사용하여 Assembly.LoadFile 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.
    

    이 예외를 해결하려면 개발 언어에서 제공하는 기능(예: Declare Visual Basic 문 또는 DllImportAttribute C# 및 F#의 키워드가 있는 특성extern)을 사용하여 DLL에 정의된 메서드에 액세스합니다.

  • 리플렉션 전용 컨텍스트가 아닌 컨텍스트에서 참조 어셈블리를 로드하려고 합니다. 다음 두 가지 방법 중 하나를 사용하여 이 문제를 해결할 수 있습니다.

    • 참조 어셈블리가 아닌 구현 어셈블리를 로드할 수 있습니다.
    • 메서드를 호출하여 리플렉션 전용 컨텍스트에서 참조 어셈블리를 로드할 Assembly.ReflectionOnlyLoad 수 있습니다.
  • DLL 또는 실행 파일은 64비트 어셈블리로 로드되지만 32비트 기능 또는 리소스를 포함합니다. 예를 들어 COM interop에 의존하거나 32비트 동적 링크 라이브러리에서 메서드를 호출합니다.

    이 예외를 해결하려면 프로젝트의 플랫폼 대상 속성을 x64 또는 AnyCPU 대신 x86으로 설정하고 다시 컴파일합니다.

  • 애플리케이션의 구성 요소는 다른 버전의 .NET을 사용하여 만들어졌습니다. 일반적으로 이 예외는 .NET Framework 1.0 또는 .NET Framework 1.1을 사용하여 개발된 애플리케이션 또는 구성 요소가 .NET Framework 2.0 SP1 이상을 사용하여 개발된 어셈블리를 로드하려고 하거나 .NET Framework 2.0 SP1 이상을 사용하여 개발된 애플리케이션을 로드하려고 할 때 발생합니다. .NET Framework 3.5는 .NET Framework 4 이상을 사용하여 개발된 어셈블리를 로드하려고 시도합니다. BadImageFormatException 컴파일 시간 오류로 보고되거나 런타임에 예외가 throw될 수 있습니다. 다음 예제에서는 단일 멤버ToProperCase가 있고 StringLib.dll이라는 어셈블리에 상주하는 클래스를 정의 StringLib 합니다.

    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
    

    다음 예제에서는 리플렉션을 사용하여 StringLib.dll이라는 어셈블리를 로드합니다. 소스 코드가 .NET Framework 1.1 컴파일러 BadImageFormatException 로 컴파일되는 경우 메서드에서 Assembly.LoadFrom throw됩니다.

    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.
    

    이 예외를 해결하려면 코드가 실행 중이고 예외를 throw하는 어셈블리와 로드할 어셈블리가 둘 다 호환되는 .NET 버전인지 확인합니다.

  • 애플리케이션의 구성 요소는 다양 한 플랫폼을 대상입니다. X86에서 ARM 어셈블리를 로드 하려는 하는 예를 들어, 애플리케이션입니다. 다음 명령줄 유틸리티를 사용하여 개별 .NET 어셈블리의 대상 플랫폼을 확인할 수 있습니다. 파일 목록은 명령줄에서 공백으로 구분된 목록으로 제공되어야 합니다.

    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++ 실행 파일을 반영할 때 이 예외가 throw될 수 있습니다. 이 예외는 대부분 C++ 컴파일러가 실행 파일에서 .Reloc 섹션이나 재배치 주소를 제거하는 경우에 발생합니다. C++ 실행 파일에서 재배치 주소를 유지하려면 링크할 때 /fixed:no 를 지정합니다.

BadImageFormatException 는 값이 0x8007000B HRESULT COR_E_BADIMAGEFORMAT를 사용합니다.

인스턴스의 초기 속성 값의 목록을 BadImageFormatException, 참조는 BadImageFormatException 생성자입니다.

생성자

BadImageFormatException()

BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

BadImageFormatException(SerializationInfo, StreamingContext)

serialize된 데이터를 사용하여 BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

BadImageFormatException(String)

지정된 오류 메시지를 사용하여 BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

BadImageFormatException(String, Exception)

지정된 오류 메시지와 해당 예외의 원인인 내부 예외에 대한 참조를 사용하여 BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

BadImageFormatException(String, String)

지정된 오류 메시지와 파일 이름을 사용하여 BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

BadImageFormatException(String, String, Exception)

지정된 오류 메시지와 해당 예외의 원인인 내부 예외에 대한 참조를 사용하여 BadImageFormatException 클래스의 새 인스턴스를 초기화합니다.

속성

Data

예외에 대한 사용자 정의 정보를 추가로 제공하는 키/값 쌍 컬렉션을 가져옵니다.

(다음에서 상속됨 Exception)
FileName

이 예외를 발생시킨 파일의 이름을 가져옵니다.

FusionLog

어셈블리 로드에 실패한 이유를 설명하는 로그 파일을 가져옵니다.

HelpLink

이 예외와 연결된 도움말 파일에 대한 링크를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
HResult

특정 예외에 할당된 코드화된 숫자 값인 HRESULT를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
InnerException

현재 예외를 발생시킨 Exception 인스턴스를 가져옵니다.

(다음에서 상속됨 Exception)
Message

오류 메시지와 이 예외를 발생시킨 파일의 이름을 가져옵니다.

Source

오류를 발생시키는 애플리케이션 또는 개체의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
StackTrace

호출 스택의 직접 실행 프레임 문자열 표현을 가져옵니다.

(다음에서 상속됨 Exception)
TargetSite

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

파일 이름, 어셈블리 캐시 로그 및 추가 예외 정보를 사용하여 SerializationInfo 개체를 설정합니다.

GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

이 예외의 정규화된 이름과 오류 메시지, 내부 예외 이름 및 스택 추적을 반환합니다.

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

추가 정보