System.BadImageFormatException An attempt was made to load a program with an incorrect format

I'm writing a plug-in for another program that is based on a public .NET API. Typically these plugins are made by creating a class library DLL that references the API assembly. Then a command class is created by inheriting from a base command class in the API assembly. The application is then set to reference the plug-in DLL file, and is then also responsible for actually firing up the custom command class when the user requests it.

However, now I'm trying to automate some code generation through System.CodeDOM, and want to create a simple console application that automatically generates new Class Types based off of types with in the API assembly.

Yet, when I try to run my application I get the following exception.

System.BadImageFormatException was unhandled Message: Could not load file or assembly 'RevitAPI, Version=2011.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Usually I need to set the target framework of a plug-in assembly to 3.5. Yet now I've found that the error above goes away if I set the target framework of my console application to 2.0. However, my console application already references other class libraries of mine that have their target framework set to 3.5. And I'd really rather not rewrite them around the 2.0 framework.


Solution 1:

It's possibly a 32 - 64 bits mismatch.

If you're running on a 64-bit OS, the Assembly RevitAPI may be compiled as 32-bit and your process as 64-bit or "Any CPU".

Or, the RevitAPI is compiled as 64-bit and your process is compiled as 32-bit or "Any CPU" and running on a 32-bit OS.

Solution 2:

If you use IIS, Go to the Application pool Select the one that your site uses and click Advance Settings Make sure that the Enable 32-Bit Applications is set to True

Solution 3:

I was having problems with a new install of VS with an x64 project - for Visual Studio 2013, Visual Studio 2015 and Visual Studio 2017:

Tools
  -> Options
   -> Projects and Solutions
    -> Web Projects
     -> Check "Use the 64 bit version of IIS Express for web sites and projects"

Solution 4:

These suggestions are accurate, but I wanted to add a note. I was stuck simply because I had multiple publishing configurations. I was editing the "Debug - Any CPU" and then deploying the "Debug - x64" configuration. Make sure you are editing and deploying the same configuration. Verify this by clicking the "Settings" tab after you begin publishing and the "Publish Web" dialog pops up. Make sure it matches the configuration you edited. (That's 4 hours of my life I will never get back!)