Sometimes, when your are coding in .NET and you are loading one or more dll within your code, you may find the BadImageFormatException error, with this message: “Could not load file or assembly or one of its dependencies. An attempt was made to load a program with an incorrect format.” . This happen because you’re trying to load a 32 bit dll in 64 bit code or vice versa.

So, what you can do?

Here some tips to follow:

  • if your project is 64 bit, check if the loading dll is 64 too. If not, change dll or set you project as x86 platform
  • if your project is 32 bit, check if the loading dll is 32 too. If not, change dll or set you project as x64 platform
  • if the previous points are respected, check this weird Visual Studio option: Any CPU – Prefer 32 bit. It suggests that it means the following:
    • If the CPU supports 32-bit processing, then the final machine code will be 32-bit (ARM or x86, doesn’t matter).
    • If not, then the machine code will be 64-bit.

    So, this option can compile your project as 32 bit. This was my case and I was loading a 64 bit dll and getting BadImageFormatException. Uncheck the option “Prefer 32 bit” solved my problem.

If you still get this exception and you are using IISExpress in Visual Studio, look this other post.