System.BadImageFormatException: Could not load file or assembly

Problem – Can’t load assembly

When you have one assembly trying to use another assembly, and they don’t have matching bitness (x64 or x86), then you’ll get an exception: either BadImageFormatException or FileLoadException.

If your project references another assembly, and the bitness doesn’t match, you’ll get this exception:

System.BadImageFormatException: ‘Could not load file or assembly <Name>. An attempt was made to load a program with an incorrect format.’

If you’re trying to dynamically load the assembly, for example using Assembly.LoadFrom(), then you’ll get the following exception:

System.IO.FileLoadException: ‘Could not load file or assembly <Name>.’

Solution – Change the assembly bitness

To fix this problem, you need to change the bitness of one of the assemblies.

How to specify the bitness of an assembly

  1. Right-click on your project > click Properties.
  2. Go to the Build tab.
  3. Change Configuration to All Configurations.
  4. Change Platform target to the appropriate value (Any CPU, x86, or x64).
Project Properties Build tab - showing the Configuration dropdown set to All Configurations and the Platform target set to Any CPU

What does platform target Any CPU mean?

When you use Any CPU, by default executables will use the same bitness as the computer, and assemblies will use the same bitness as the process they are being loaded into. For example, if you have a console app using Any CPU, and you’re launching it on a 64-bit computer, the console app will be loaded as 64-bit executable. Any assemblies it references that are using Any CPU will also be loaded as 64-bit assemblies.

Which platform target should I use? Any CPU, x86, or x64?

If you’re not using a third-party assembly

You control both assemblies and can change them both to use Any CPU.

If you’re using a third-party assembly

Most likely you’re using a third-party assembly that has its bitness explicitly set to either x64 or x86. You can’t change the third-party assemby’s bitness, but you can change your own. What you change it to will depend on what the third-party assembly is using and what computer you’re trying to load it on.

The following table shows the four scenarios.

32-bit computer64-bit computer
32-bit assemblyChange your own assembly to Any CPU.Change your own assembly to x86.

(or try to get a 64-bit version of the third-party assembly so you don’t have to change everything to x86)
64-bit assemblyThe computer won’t be able to load this third-party assembly.

You’ll have to get a 32-bit version of the third-party assembly.
Change your own assembly to Any CPU.

Note: If you have to explicitly set the bitness of one assembly in the program, it will have a ripple effect and you’ll have to make sure the process is running in the right bitness too.

Leave a Comment