System.BadImageFormatException on 64-bit OS

I got the following exception when running the unit tests as part of a local build of our .NET project today:

System.BadImageFormatException : Could not load file or assembly '(assembly name)' or one of its dependencies. 
An attempt was made to load a program with an incorrect format.

This seemed a bit odd, because the build was working on every other machine. Even odder, the build and tests ran fine within Visual Studio.

Turns out this occurs when the CLR tries to load an assembly that contains unmanaged code built targeting a different platform. In my case, I was running it on my new machine which has 64-bit Vista, but one of the referenced assemblies contained native code compiled targeting x86. It was running fine in Visual Studio because VS is a 32-bit app, and so was calling everything in 32-bit mode via WoW64.

The solution? Build both 32-bit and 64-bit versions of the assembly causing the problem, or force our project to always run in 32-bit mode (within WoW64 on x64 machines) by specifically setting the platform target to x86 in the Visual Studio project build options (by default this is set to "Any CPU").

Hope this saves someone some hair-tearing. :)

Update: I have found the Corflags tool invaluable for flagging a DLL as needing to run under the 32 bit CLR. This is useful when you don’t have the source to recompile the app, and has been put to good use getting the old, free version of NCover to run on a 64-bit bit OS. A good write up on Corflags is here.