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:
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=220.127.116.11, 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=18.104.22.168, 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=22.214.171.124, Culture=neutral, PublicKeyToken=null (Fully-specified) LOG: Appbase = file:///c:/Dev/TeamE/bin/Release/ LOG: Initial PrivatePath = NULL Calling assembly : XxxDevicesService, Version=126.96.36.199, 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:
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.
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.
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.
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.
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.
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.
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.
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-188.8.131.52" newVersion="184.108.40.206" /> </dependentAssembly>
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
A good place to put this is right after the
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.
For anyone who may arrive here at a later time...
For Desktop solution I got
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
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.
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.
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.
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>
User contributions licensed under CC BY-SA 3.0