The cause of a
System.BadImageFormatException is a common question received by our developer support department. At first glance, some LEADTOOLS users think the
BadImageFormatException is a LEADTOOLS specific exception because LEADTOOLS is an imaging SDK and “Image” is in the name of the exception. However, the exception has nothing to do with LEADTOOLS being an imaging SDK.
This exception is thrown when a process tries to load an assembly that is built for an incompatible architecture. The MSDN description of the exception is:
This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) doesn’t conform to the format that the common language runtime expects.
Plainly, this means that a 64-bit process is trying to load an assembly marked as 32-bit or vice versa. To fix this exception, there are a couple of things to check.
First, check to ensure the build target setting in Visual Studio is set to flag the assembly as x86 or x64, and not Any CPU. (See MSDN for more information about the
/platform flag). Because most of LEADTOOLS is written in managed C++, we have to provide binaries that target either x86 or x64. If you are using LEADTOOLS in your project, we recommend to go ahead and build for a specific target. Unless you need to allocate a tremendous amount of memory, select x86 because it has less memory overhead and is more portable than x64 (i.e., an x86 application can run on x86 and x64 versions of Windows).
If the build is targeting x86, and you still get the exception, then check the referenced assemblies of the project to make sure an x64 version was not mistakenly added. If all of the reference paths are pointing to x86 versions of the assemblies, then look at other assemblies in the BIN folder to make sure they are all x86 compatible and an x64 assembly was not copied by mistake.
The easiest way to check the architecture of LEADTOOLS assemblies is in Windows explorer. Add the Product name column to Windows Explorer. The LEADTOOLS assemblies will clearly list the architecture in the product name. Win32 and Any CPU together is okay. x64 and Any CPU together is okay. Win32 and x64 in the same folder is bad.
There could be scenarios that throw this exception, but the ones listed usually cover 99% of the cases I have ever come across. If you know of other causes, share them with me in the comments!
UPDATE: BadImageFormatException and the Visual Studio Designer
Walter in the support department just reminded me that Visual Studio is a 32-bit process. This means that if you target x64, you could also get the
BadImageFormatException in the designer. The solution seems to be that you have to target x86 when using the designer. Then, if you need x64 for some reason, you can change the platform target to x64 once all of your designer work is complete.