128

I have a Windows service written in C# using Visual Studio 2010 and targeting the full .NET Framework 4. When I run from a Debug build the service runs as expected. However, when I run it from a Release build I get a System.BadImageFormatException (details below). I've been searching the internet for a solution but so far every thing I've found hasn't helped me find a solution.

The problem exists on both Windows 7 64-bit (dev) and Windows XP SP3 32-bit (target) systems.

Here is what I've tried so far:

  • Verified build settings such as Platform Target are all the same (x86).
  • Used peverify with the /verbose option to ensure the assembly binaries were valid.
  • Uses fuslogvw to look for any loading issues.
  • Used CheckAsm to look for missing files or assembiles.

All of these checks didn't change anything. I've included the full text of the exception information below, with some of the names changed to protect the secrets of my corporate masters.

System.BadImageFormatException was unhandled
  Message=Could not load file or assembly 'XxxDevices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
  Source=XxxDevicesService
  FileName=XxxDevices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  FusionLog=Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  c:\Dev\TeamE\bin\Release\XxxDevicesService.vshost.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: User = XXX
LOG: DisplayName = XxxDevices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///c:/Dev/TeamE/bin/Release/
LOG: Initial PrivatePath = NULL
Calling assembly : XxxDevicesService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\TeamE\bin\Release\XxxDevicesService.vshost.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///c:/TeamE/bin/Release/XxxDevices.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

  StackTrace:
       at XxxDevicesService.Program.Main(String[] args)
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
  • are you mixing native code / .net at all? – Keith Nicholas Jan 25 '12 at 01:11
  • 1
    You are on the right track that this exception is associated with x86/x64 bit differences. I assume this is not a web application right? Also, what type of assembly is `XxxDevicesService`? Is it compiled for a specific platform (e.g. 32 bit)? If so, then you must compile your platform to 32 bit. – Reddog Jan 25 '12 at 01:14
  • https://support.microsoft.com/en-us/kb/967163 – Palec Dec 01 '15 at 09:29
  • If the answers here did solve your issue please also note that the version of "WebView2Loader.dll" which is in use is very crucial. I had the same problem with "Microsoft.WebView2.FixedVersionRuntime.101.0.1210.39.x64" when I tried to use the WebView2 component in the MMC Snap-Ins with types of "HTMLView" or "FormView". – amirfg May 18 '22 at 07:52
  • I just copied the abovementioned dll file (version 1.0.1248.0, size=157640 bytes) in a proper path that was accessible for the project (you could just put it beside your project output files first to test it) and then WebView2 browser started to function as expected. Microsoft error messages sometimes (at least in my case) was a little bit misleading and did not convey enough and to the point information. – amirfg May 18 '22 at 07:52
  • I received "BadImageFormatException" that normally occurs when you mix platform targets (for example using a dll file compiled in X64 in an application that targeted for x86 or vice versa) or mix native code and .NET but that was not my problem at all. I hope this help one who may stuck in. – amirfg May 18 '22 at 07:52

25 Answers25

138

Verified build settings such as Platform Target are all the same (x86).

That's not what the crash log says:

Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework64

Note the 64 in the name, that's the home of the 64-bit version of the framework. Set the Target platform setting on your EXE project, not your class library project. The XxxDevicesService EXE project determines the bitness of the process.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
63

After I stopped banging my head on the desk thinking of the entire week I spent running down this problem, I am sharing what worked for me. I have Win7 64 bit, 32-bit Oracle Client, and have my MVC 5 project set to run on x86 platform because of the Oracle bitness. I kept getting the same errors:

Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I reloaded the NuGet packages, I used copies of the DLLs that worked for others in different apps, I set the codebase in the dependent assembly to point to my project's bin folder, I tried CopyLocal as true or false, I tried everything. Finally I had enough else done I wanted to check in my code, and as a new contractor I didn't have subversion set up. While looking for a way to hook it into VS, I tripped over the answer. What I found worked was unchecking the following:

Tools
-> Options
--> Projects and Solutions
---> Web Projects
----> Use the 64 bit version of IIS Express for web sites and projects

alamoot
  • 1,966
  • 7
  • 30
  • 50
Joey Morgan
  • 823
  • 6
  • 9
  • 5
    What a life saver!! Thank you. For me I had to actually check this, since my project is effectively x64. Thanks again!!! – viper Oct 17 '16 at 14:14
  • After all the help I have received here, I am very glad to have been able to pay some of it forward! – Joseph Morgan Oct 20 '16 at 23:06
  • 3
    For those using Local IIS, make sure your app pool's "Enable 32-Bit Applications" (under Advanced Settings) is set to **True**. – Eric Eskildsen Mar 15 '17 at 18:46
  • An addenum to @EricEskildsen's comment above about "enable 32-bit applications" in the application pool, even if you don't want to do that in the live environment, flipping that switch can provide additional clues as to whether you *are* facing a 32-bit/64-bit problem or something else. – user Mar 16 '17 at 08:11
  • Boom! That was it. – itslittlejohn May 11 '17 at 14:05
  • Thank you! The problem is this is not a project level configuration, so each new developer will get the same issue until we remember to check the box – vvvlad Oct 04 '18 at 08:37
  • If you have multiple developers, have them open a blank project, check it, and save as a template. Then they can share that as a starting point for new projects instead of the one that comes out of the box. Other settings could be set up at that time too, and the template shared with the team. Just a thought--I just got back from a 3 hour drive following a 4-hour interview, so I am not testing this. If they each have their own IIS config, they still only have to check it once for their local IIS if you do it the App Pool way instead. Curious to know your results. – Joey Morgan Nov 06 '18 at 04:45
  • In my Visual Studio, the option 'Use the 64 bit version of IIS Express for Web Sites and Projects' under Tools=>Options menu=>Projects and Solutions => Web Projects is greyed out/disabled. My PC's sys info shows x64-based PC. What does this indicate? I'm guessing my VS cannot run x64-based apps ... – Anne Bailly Dec 22 '21 at 17:54
  • Thank you for sharing this answer, it saved lot of hustle – Sid M Apr 14 '23 at 11:19
29

What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.

Lucy Zhang
  • 291
  • 3
  • 2
  • 1
    you are the savior. +1 – Amit Kumar Sep 03 '18 at 09:32
  • I reinstalled VS and was troubleshooting this problem (thank you - this solution worked). Moral of the story for me is if I know I hadn't changed any code to begin with, maybe I should look at the configuration of VS first. – taylorswiftfan Jan 31 '19 at 01:54
  • @Lucy check box 'Use the 64 bit version of IIS Express for Web Sites and Projects' is desabled – k_kumar May 13 '19 at 10:57
  • Please tell Lucy – k_kumar May 17 '19 at 12:50
  • Indeed you are a savior! My problem was that I was getting this error while loading Mapserver's Mapscript DLL. Nothing else worked for me: No change in the target platform to x86 and no copying tons of DLL to the project's Bin folder helped. But when I CHECKED to make IISExpress to run as 64 BIT then it worked! I don't know why but it did. Going to check in the regular IIS as well.. – IrfanClemson May 03 '21 at 15:56
  • EDIT: In case of IIS, I had to NOT allow 32 Bit for the application's Pool. FYI. – IrfanClemson May 03 '21 at 16:20
13

Just setting the platform target to x86 only did not solve it for me. I had to Change Bitness to x86 in my project properties

As follows:

Properties -> Web -> Bitness

enter image description here

Towernter
  • 210
  • 2
  • 10
12

It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.

Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.

Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.

These might just save you lot of time before you start trying different things with project properties to overcome the error.

purvin
  • 144
  • 1
  • 3
10

I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine

Motorhead
  • 928
  • 6
  • 16
  • 1
    Same here. This did the trick. Referenced a 64-bit assembly and the active build configuration was set to Any CPU but because of this "prefer 32-bit" setting assumably 32-bit was used running the application and caused the troubles. – Youp Bernoulli Jun 30 '16 at 11:49
  • Picked *Any CPU* instead of *x86* in Debug mode and worked like a charm. – Cardi DeMonaco Jr Oct 03 '19 at 14:20
8

You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

When trying to launch the debug of the application you will get the BadImageFormatException.

Removing the line declaring the v2.0 version will clear the error.

I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.

Cédric V
  • 1,729
  • 2
  • 21
  • 28
7

Background

We started getting this today when we switched our WCF service from AnyCPU to x64 on a Windows 2012 R2 server running IIS 6.2.

First we checked the only referenced assembly 10 times, to ensure it was not actually an x86 dll. Next we checked the application pool many times to ensure it was not enabling 32 bit applications.

On a whim I tried toggling the setting. It turns out the application pools in IIS were defaulting to an Enable 32-Bit Applications value of False, but IIS was ignoring it on our server for some reason and always ran our service in x86 mode.

Solution

  • Select the app pool.
  • Choose Set Application Pool Defaults... or Advanced Settings....
  • Change Enable 32-Bit Applications to True.
  • Click OK.
  • Choose Set Application Pool Defaults... or Advanced Settings... again.
  • Change Enable 32-Bit Applications back to False.
  • Click OK.
JoelC
  • 3,664
  • 9
  • 33
  • 38
4

I fixed this issue by changing the web app to use a different "Application Pool".

Cocu_1012
  • 109
  • 3
4

For anyone who may arrive here at a later time....Nothing worked for me. All my assemblies were fine. I had an app config in one of my Visual Studio Projects that shouldn't have been there. So make sure your app config file is needed.

I deleted the extra app config and it worked.

McSick
  • 116
  • 1
  • 1
  • 6
4

Target build x64 Target Server Hosting IIS 64 Bit

If the application build is targeting 64-Bit OS then on the 64-Bit server hosting the IIS,Set the enable 32 bit application on the app pool running the website/web application to false.

enter image description here

nobody
  • 10,892
  • 8
  • 45
  • 63
3

When building apps for 32-bit or 64-bit platform (My experience is with Visual Studio 2010), don't rely on the Configuration Manager to set the correct platform for the executable. Even if the CM has x86 selected for the application, check the project properties (Build tab): it might still say "Any CPU" there. And if you run an "Any CPU" executable on a 64-bit platform, it will run in 64-bit mode and refuse to load your accompanying DLLs that were built for the x86 platform.

2

Determine the application pool used by the application and set the property of by setting Enable 32 bit applications to True. This can be done through advance settings of the application pool.

Anand
  • 31
  • 1
1

For anyone who may arrive here at a later time...
For Desktop solution I got BadImageFormatException exception.
All project's build options was fine (all x86). But StartUp project of solution was changed to some other project(class library project).

Changing StartUp project to the original(.exe application project) was a solution in my case

Fabio
  • 31,528
  • 4
  • 33
  • 72
1

Remove your dependency on System.Runtime in your Web.Config, it worked for me:

<dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
</dependentAssembly>
Ajean
  • 5,528
  • 14
  • 46
  • 69
Niclas
  • 11
  • 2
1

For .NET Core, there is a Visual Studio 2017 bug that can cause the project properties Build page to show the incorrect platform target. Once you discover that the problem is, the workarounds are pretty easy. You can change the target to some other value and then change it back.

Alternatively, you can add a runtime identifier to the .csproj. If you need your .exe to run as x86 so that it can load a x86 native DLL, add this element within a PropertyGroup:

<RuntimeIdentifier>win-x86</RuntimeIdentifier>

A good place to put this is right after the TargetFramework or TargetFrameworks element.

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
1

I am surprised that no-one else has mentioned this so I am sharing in case none of the above help (my case).

What was happening was that an VBCSCompiler.exe instance was somehow stuck and was in fact not releasing the file handles to allow new instances to correctly write the new files and was causing the issue. This became apparent when I tried to delete the "bin" folder and it was complaining that another process was using files in there.

Closed VS, opened task manager, looked and terminated all VBCSCompiler instances and deleted the "bin" folder to get back to where I was.

Reference: https://developercommunity.visualstudio.com/content/problem/117596/vbcscompilerexe-process-stays-runing-after-exiting.html

George
  • 1,224
  • 12
  • 21
1

I had this happen because somehow AnyCPU's Platform Target for one project got set to x86 in Properties > Build. Changing it there fixed the issue.

Tridus
  • 5,021
  • 1
  • 19
  • 19
1

In API project I am facing the same issue. Actually I am using VS2019. My project is perfectly built but facing this when running through IIS.

And also API application doesn't connected by showing this error This works for me. vs2019-tools-options

VS2019 -> Tools -> Options -> Projects and Solutions -> Web Projects -> Enable "Use the 64bit version of IIS Express for Websites and Projects

0

When I faced this issue the following solved it for me:

I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Ali Nejad
  • 23
  • 8
0

This error "Could not load file or assembly 'example' or one of its dependencies. An attempt was made to load a program with an incorrect format" is typically caused by an incorrect application pool configuration.

  1. Ensure that the AppPool your site is currently running on has "Enable 32-Bit Applications" set to False.
  2. Ensure you are using the correct version for your platform.
  3. If you are getting this error on a web site, ensure that your application pool is set to run in the correct mode (3.0 sites should run in 64 bit mode)
  4. You should also make sure that the reference to that assembly in visual studio is pointing at the correct file in the packages folder.
  5. Ensure you have the correct version of the dll installed in the GAC for 2.0 sites.
  6. This can also be caused by WSODLibs being promoted with the web project.
Ben Petersen
  • 471
  • 4
  • 15
0

For CI/CD, MSBuild, DevEnv

Your build-machine log shows - MSB3270 ... MSIL vs AMD64.

warning MSB3270: There was a mismatch between the processor architecture of the project
  being built "MSIL" and the processor architecture of the reference
  "C:\build-machine\my-solution\My-1\bin\Release\My-1.dll", "AMD64".
This mismatch may cause runtime failures.
Please consider changing the targeted processor architecture of your project through
  the Configuration Manager so as to align the processor architectures between your
  project and references, or take a dependency on references with a processor architecture
  that matches the targeted processor architecture of your project. [C:\build-machine\my-solution\My-2.csproj]

You have Enable 32-Bit Applications value set to True in your site's IIS App-pool advanced settings.

You site shows the following error after a deployment

An attempt was made to load a program with an incorrect format ... 
... BadImageFormatException

You can fix it by setting Enable 32-Bit Applications to False, but you have to use 32-Bit mode.

Steps to check and fix

Something from the following steps definitely helped me.

*. Open your Visual Studio solution folder in VSCode and search for something like this

<Target Name="AfterBuild">
    <MSBuild Condition=" '$(Platform)' == 'x86' " Projects="$(MSBuildProjectFile)"
        Properties="Platform=x64;PlatFormTarget=x64" RunEachTargetSeparately="true" />
</Target>

Consider to delete it from your project files (.csproj)

*. Open your solution in VS and open Configuration Manager.
Consider to delete x64 platform from all solution configurations.

*. For those who have multiple build steps to build project by project.
Consider to change build older to run Any Cpu (MSIL), x86 projects before x64 projects. Or configure separation of project's Output path for different platforms.
Be careful during creation of deployment packages. Consider to accumulate different build outputs between project build runs.

*. Consider to clean out all x64 stuff from your project files for projects that should have x64 platform. It is something like this

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    ....
</PropertyGroup>
it3xl
  • 2,372
  • 27
  • 37
0

I just deleted the file. ¯\_(ツ)_/¯

In the log, before the stacktrace, it says the following, so I just deleted said DLL, rebuilt the solution (Build > Rebuild Solution), noticed that the DLL was not replaced (maybe it wasn't supposed to be there at all), and now everything works.

LOG: Attempting download of new URL file:///c:/TeamE/bin/Release/XxxDevices.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.
l3oxy
  • 13
  • 3
0

Please also note that the version of "WebView2Loader.dll" which is in use is very crucial. I had almost the same problem with "Microsoft.WebView2.FixedVersionRuntime.101.0.1210.39.x64" when I tried to use the WebView2 component in the MMC Snap-Ins with types of "HTMLView" or "FormView".

I just copied the abovementioned dll file (version 1.0.1248.0, size=157640 bytes) in a proper path that was accessible for the project (you could just put it beside your project output files first to test it) and then WebView2 browser started to function as expected. Microsoft error messages sometimes (at least in my case) was a little bit misleading and did not convey enough and to the point information.

I received "BadImageFormatException" that normally occurs when you mix platform targets (for example using a dll file compiled in X64 in an application that targeted for x86 or vice versa) or mix native code and .NET but that was not my problem at all. I hope this help one who may stuck in.

amirfg
  • 272
  • 2
  • 6
  • 21
0

Just in case someone is stuck with this exception using Visual C++ (when there is no VS installed on target machine):

  1. VC++ needs runtime
  2. All your code should be compiled in Release!!!
Ignatella
  • 61
  • 1
  • 6