.NET runtime threw BadImageFormatException when loading an assembly
System.BadImageFormatException: Could not load file or assembly '<assembly>' or one of its dependencies. An attempt was made to load a program with an incorrect format.
The .NET runtime threw a BadImageFormatException because it tried to load an assembly or DLL that was compiled for a different CPU architecture than the current process, or because the file is not a valid .NET assembly at all. The most common cause is a mismatch between a 32-bit (x86) DLL and a 64-bit process (or vice versa).
System.BadImageFormatException: Could not load file or assembly '<assembly>' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Why it happens
A 32-bit (x86) native DLL or .NET assembly is being loaded by a 64-bit process.
A 64-bit DLL is being loaded by a 32-bit process.
The project's Platform Target is set to x86 or x64 and conflicts with a referenced assembly compiled for the other architecture.
A native DLL referenced via P/Invoke (DllImport) is the wrong bitness for the process.
The file being loaded is corrupted, incomplete, or is not actually a valid PE/COFF image.
In unit test projects, the test runner is running as 64-bit but a dependency requires 32-bit, or the test project's platform target is mismatched.
How to fix it
In Visual Studio, check the Platform Target of the project that throws the exception: Project Properties > Build > Platform target. Set it to AnyCPU unless you have a specific reason for x86 or x64.
If your project references native (unmanaged) DLLs, ensure both x86 and x64 versions of the native DLL are included and that the correct one is loaded at runtime based on `IntPtr.Size` or `Environment.Is64BitProcess`.
For unit test projects, set the test runner to the correct bitness: in Visual Studio Test settings, change the test platform target to match the dependency requirements.
Inspect the DLL causing the exception using `dumpbin /headers <file.dll>` on the command line to confirm its machine type (x86=0x14C, x64=0x8664).
Verify the file has not been corrupted: compare its hash against a known-good version if available.
When publishing, ensure the correct architecture-specific native binaries are included for the target runtime identifier (RID) in your publish profile.