Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 4
System
Collapse All/Expand All Collapse All
.NET Framework Class Library
BadImageFormatException Class

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.

System..::.Object
  System..::.Exception
    System..::.SystemException
      System..::.BadImageFormatException

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class BadImageFormatException _
    Inherits SystemException
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class BadImageFormatException : SystemException
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class BadImageFormatException : public SystemException
F#
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type BadImageFormatException =  
    class
        inherit SystemException
    end

The BadImageFormatException type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryBadImageFormatException()()()Initializes a new instance of the BadImageFormatException class.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryBadImageFormatException(String)Initializes a new instance of the BadImageFormatException class with a specified error message.
Protected methodBadImageFormatException(SerializationInfo, StreamingContext)Initializes a new instance of the BadImageFormatException class with serialized data.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryBadImageFormatException(String, Exception)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.
Public methodBadImageFormatException(String, String)Initializes a new instance of the BadImageFormatException class with a specified error message and file name.
Public methodBadImageFormatException(String, String, Exception)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.
Top
  NameDescription
Public propertyDataGets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public propertyFileNameGets the name of the file that causes this exception.
Public propertyFusionLogGets the log file that describes why an assembly load failed.
Public propertyHelpLinkGets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Protected propertySupported by the XNA FrameworkSupported by Portable Class LibraryHResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryInnerExceptionGets the Exception instance that caused the current exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryMessageGets the error message and the name of the file that caused this exception. (Overrides Exception..::.Message.)

In XNA Framework 3.0, this member is inherited from Exception..::.Message.


In Portable Class Library Portable Class Library, this member is inherited from Exception..::.Message.
Public propertySourceGets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryStackTraceGets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public propertyTargetSiteGets the method that throws the current exception. (Inherited from Exception.)
Top
  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetObjectDataSets the SerializationInfo object with the file name, assembly cache log, and additional exception information. (Overrides Exception..::.GetObjectData(SerializationInfo, StreamingContext).)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the runtime type of the current instance. (Inherited from Exception.)

In XNA Framework 3.0, this member is inherited from Object..::.GetType()()().


In Portable Class Library Portable Class Library, this member is inherited from Object..::.GetType()()().
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace. (Overrides Exception..::.ToString()()().)

In XNA Framework, this member is overridden by ToString()()().


In Portable Class Library, this member is overridden by ToString()()().
Top
  NameDescription
Protected eventSerializeObjectStateOccurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top

This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) does not conform to the format that is expected by the common language runtime. In particular, the exception is thrown under the following conditions:

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

    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. This may require modifying the Path environment variable or providing a fully qualified path to the correct executable.

  • An attempt is made to load an unmanaged dynamic link library or executable (such as a Windows system DLL) as if it were a .NET Framework assembly. The following example illustrates this by using the Assembly..::.LoadFile method to load Kernel32.dll.

    Visual Basic
    ' 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.
    
    C#
    // 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.
    

    To address this exception, access the methods defined in the DLL by using the features provided by your development language, such as the Declare statement in Visual Basic or the DllImportAttribute attribute with the extern keyword in C#.

  • A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources. For example, it relies on COM interop or calls methods in a 32-bit dynamic link library.

    To address this exception, set the project's Platform target property to x86 (instead of x64 or AnyCPU) and recompile.

  • Components have been created using different versions of the .NET Framework. Typically, this exception occurs when an application or component that was developed using the .NET Framework 1.0 or the .NET Framework 1.1 attempts to load an assembly that was developed using the .NET Framework 2.0 SP1 or later, or when an application that was developed using the .NET Framework 2.0 SP1 or .NET Framework 3.5 attempts to load an assembly that was developed using the .NET Framework 4. The BadImageFormatException may be reported as a compile-time error, or the exception may be thrown at run time. The following example illustrates this scenario. It defines a StringLib class that has a single member, ToProperCase, and that resides in an assembly named StringLib.dll.

    Visual Basic
    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
    
    C#
    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.
    

    The following example uses reflection to load an assembly named StringLib.dll. If the source code is compiled with a .NET Framework 1.1 compiler, a BadImageFormatException is thrown by the Assembly..::.LoadFrom method.

    Visual Basic
    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.
    
    C#
    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);
       }
    }
    

    To address this exception, ensure that the assembly from which the exception is thrown attempts to load an assembly that was developed by using a compatible version of the .NET Framework.

BadImageFormatException uses the HRESULT COR_E_BADIMAGEFORMAT, which has the value 0x8007000B.

For a list of initial property values for an instance of BadImageFormatException, see the BadImageFormatException constructors.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
64-Bit DLL's      Reddgum   |   Edit   |   Show History
If you include DLL's from other projects, check the specific project's properties under BUILD and then look at the platform target. You can't mix an x86 application with x64 DLL's.
Tags What's this?: Add a tag
Flag as ContentBug
This can be caused by building x64 Setup project that uses a managed custom action      JohnFox147   |   Edit   |   Show History
This exception can happen you you add a 64-bit managed custom action to a Setup project. See the section '64-bit managed custom actions throw a System.BadImageFormatException exception': http://msdn.microsoft.com/en-us/library/kz0ke5xt.aspx
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker