ChatGPT解决这个技术问题 Extra ChatGPT

Troubleshooting BadImageFormatException

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?
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.
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".
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.

H
Hans Passant

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.


And while you're checking the EXE project- check both Debug and Release. :/
a
alamoot

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


What a life saver!! Thank you. For me I had to actually check this, since my project is effectively x64. Thanks again!!!
After all the help I have received here, I am very glad to have been able to pay some of it forward!
For those using Local IIS, make sure your app pool's "Enable 32-Bit Applications" (under Advanced Settings) is set to True.
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.
Boom! That was it.
L
Lucy Zhang

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.


you are the savior. +1
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.
@Lucy check box 'Use the 64 bit version of IIS Express for Web Sites and Projects' is desabled
Please tell Lucy
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..
p
purvin

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.


I came across a similar problem and your answer was the solution for mine. My app.config had different supported runtime.
T
Towernter

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

https://i.stack.imgur.com/liYQo.png


this did the trick for me after switching from Visual Studio 2019 to 2022, tnx!
You are welcome
N
N.S.

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


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.
Picked Any CPU instead of x86 in Debug mode and worked like a charm.
C
Cédric V

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.


J
JoelC

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.


C
Cocu_1012

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


M
McSick

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.


Fixed it for me. My App.config was setting my .NET 4.5.1 app to the 2.0 CLR!
n
nobody

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.

https://i.stack.imgur.com/szkFY.png


J
Jeremy Tinkler

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.


A
Anand

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.


F
Fabio

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


A
Ajean

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>

For me it was the System.Net.Http. Thanks for it.
E
Edward Brey

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.


G
George

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


My solution was also to delete all the bin and debug directories.
Deleting the bin and obj directories solved it for me.
T
Tridus

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.


r
ryanyuyu

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.


B
Ben Petersen

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.

Ensure that the AppPool your site is currently running on has "Enable 32-Bit Applications" set to False. Ensure you are using the correct version for your platform. 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) You should also make sure that the reference to that assembly in visual studio is pointing at the correct file in the packages folder. Ensure you have the correct version of the dll installed in the GAC for 2.0 sites. This can also be caused by WSODLibs being promoted with the web project.


i
it3xl

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>

l
l3oxy

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.

a
amirfg

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.


S
Santhoshkumar

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