[c#] 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: 

This question is related to c# .net exception

The answer is


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>

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.


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.


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


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.


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


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.

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.


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


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


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.


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.


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


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.


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


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.

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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback