System.BadImageFormatException

What in the world is a System.BadImageFormatException??? I didn’t know either. And it drove me insane because I could not seem to figure out what was causing this error only when I deploy to a UAT site. It worked fine in DEV and on other servers I tested. The only difference between the server environments was that one server was 32 bit and the other was 64 bit. Here is the message I received running the app on 64 bit Windows Server 2003:

System.BadImageFormatException: Could not load file or assembly ‘Assembly.Name.dll’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

So basically, this means that a 32 bit assembly is being loaded into 64 bit runtime or visa-versa. The fix?…well that depends. If you must run your app in 32-bit mode then look into using WOW64 on your server to run the application in 32 bit mode. Also this may be the fix if you have your assemblies set to compile in “Any CPU” – to prevent IIS from pushing the assembly to the wrong mode.

However these fixes did not solve my problem. Mine was a little reversed. I could not enable 32 bit mode on the server (for some other stupid reasons….I will leave it at that). I eventually discovered one of my assemblies was compiling to x86 instead of Any CPU. After changing this and deploying I double checked that all assemblies were Any CPU (by using this procedure https://travisgosselin.com/blog/?p=88  and validating the 32 bit was set to zero for all assemblies). And finally everything began working nicely.

Moral of the problem? – have in mind your UAT / PROD environment when compiling your app and validate the environments match.

The key that tipped me off in this direction I found at: http://www.atalasoft.com/kb/article.aspx?id=10165

Leave a Reply