[.net] System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I am trying to install a Windows service using InstallUtil.exe and am getting the error message

System.BadImageFormatException: Could not load file or assembly '{xxx.exe}' or one of its dependencies. An attempt was made to load a program with an incorrect format.

What gives?


EDIT: (Not by OP) Full message extracted from dup getting way more hits [for googleability]:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe C:\xxx.exe Microsoft (R) .NET Framework Installation utility Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved.

Exception occurred while initializing the installation: System.BadImageFormatException: Could not load file or assembly 'file:///C:\xxx.exe' or one of its dependencies. An attempt was made to load a program with an incorrect format..

This question is related to .net windows-services x86 64-bit x86-64

The answer is


I had the same issue. I using the standard command for execution. It was calling the X64 ro run against X86 tests. I needed to specify the X86 and not the X64 version of the nunit-runner.


The problem is that every System.BadImageFormatException: Could not load file or assembly including the ones not associated with installutil.exe at all point to this very thread.

  1. If your issue is related to WindowsBase or PresentationFramework dlls and you got analyzers installed make sure to either have them installed for all of the projects in your solution or for none of them.

    enter image description here

  2. Reference the entire framework in .csproj file of your library rather than just the two dlls:

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    
      <PropertyGroup>
        <OutputType>Library</OutputType>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <RazorLangVersion>3.0</RazorLangVersion>
        <UseWpf>True</UseWpf>
      </PropertyGroup>
    
  3. Remove bin and obj dirs, clean solution and rebuild.


I have faced this issue today. In my case, my application's (had a reference to a 64-bit dll) platform target was set to AnyCPU but Prefer 32-bit check box under platform target section was ticked by default. This was the problem and worked all fine after un-checking Prefer 32-bit option.


OK, this is the problem I had, and, what fixed it, seems very relevant to the above.

I am using Visual Studio 2010 Express. I wrote a test service that didn't really do anything. It was just practice for the real thing later.

I wrote the service and tried to install it using installutil.exe and got the following error:

System.BadImageFormatException: Could not load file or assembly '{filename.exe}' or one of its dependencies. An attempt was made to load a program with an incorrect format.

So far the same as the original author.

Ruben's observation above about the 32 bit output of Visual Studio 2010 was the saviour here.

I used the 64-bit version of the installutil.exe and sure enough, the output of the Visual Studio 2010 build was 32-bit. Just to add a little extra value here, you can find the 32-bit version of the latest .NET framework and the associated installutil.exe in the C:\Windows\Microsoft.NET\framework folder. Using this version of the installutil.exe fixed my problem; the service installed without a hitch!

I hope this helps someone else out there.


In the case of having this message in live tests, but not in unit tests, it's because selected assemblies are copied on the fly to $(SolutionDir)\.vs\$(SolutionName)\lut\0\0\x64\Debug\. But sometime few assemblies can be not selected, eg., VC++ dlls in case of interop c++/c# projects.

Post-build xcopy won't correct the problem, because the copied file will be erased by the live test engine.

The only workaround to date (28 dec 2018), is to avoid Live tests, and do everything in unit tests with the attribute [TestCategory("SkipWhenLiveUnitTesting")] applied to the test class or the test method.

This bug is seen in any Visual Studio 2017 up to 15.9.4, and needs to be addressed by the Visual Studio team.


Summarizing, both the Build and Project\Build\Platform has to be set to x64 in order to successfully install 64 bit service on 64 bit system.


After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.


I have faced this issue today. In my case, my application's (had a reference to a 64-bit dll) platform target was set to AnyCPU but Prefer 32-bit check box under platform target section was ticked by default. This was the problem and worked all fine after un-checking Prefer 32-bit option.


My issue was different. This occurred after an unexpected shutdown of my windows 7 machine. I performed a clean solution and it ran as expected.


Summarizing, both the Build and Project\Build\Platform has to be set to x64 in order to successfully install 64 bit service on 64 bit system.


My issue was different. This occurred after an unexpected shutdown of my windows 7 machine. I performed a clean solution and it ran as expected.


In my case I used Framework64 like below

cd\
cd "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
installutil.exe "C:\XXX\Bin\ABC.exe"
pause

The problem is that every System.BadImageFormatException: Could not load file or assembly including the ones not associated with installutil.exe at all point to this very thread.

  1. If your issue is related to WindowsBase or PresentationFramework dlls and you got analyzers installed make sure to either have them installed for all of the projects in your solution or for none of them.

    enter image description here

  2. Reference the entire framework in .csproj file of your library rather than just the two dlls:

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    
      <PropertyGroup>
        <OutputType>Library</OutputType>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <RazorLangVersion>3.0</RazorLangVersion>
        <UseWpf>True</UseWpf>
      </PropertyGroup>
    
  3. Remove bin and obj dirs, clean solution and rebuild.


We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.


Target build x64 Target Server Hosting IIS 64 Bit

Right Click appPool hosting running the website/web application and set the enable 32 bit application = false.

enter image description here


OK, this is the problem I had, and, what fixed it, seems very relevant to the above.

I am using Visual Studio 2010 Express. I wrote a test service that didn't really do anything. It was just practice for the real thing later.

I wrote the service and tried to install it using installutil.exe and got the following error:

System.BadImageFormatException: Could not load file or assembly '{filename.exe}' or one of its dependencies. An attempt was made to load a program with an incorrect format.

So far the same as the original author.

Ruben's observation above about the 32 bit output of Visual Studio 2010 was the saviour here.

I used the 64-bit version of the installutil.exe and sure enough, the output of the Visual Studio 2010 build was 32-bit. Just to add a little extra value here, you can find the 32-bit version of the latest .NET framework and the associated installutil.exe in the C:\Windows\Microsoft.NET\framework folder. Using this version of the installutil.exe fixed my problem; the service installed without a hitch!

I hope this helps someone else out there.


The key is to set match processor settings for the project which are at two places.

enter image description here

And also make sure the architecture settings is same in Test menu >> Test Settings >> Default Processor Architecture >> as show below.

enter image description here

This is for VS2013 but maybe same for other versions too.

Update - For VS2019:

enter image description here


We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.


Target build x64 Target Server Hosting IIS 64 Bit

Right Click appPool hosting running the website/web application and set the enable 32 bit application = false.

enter image description here


I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

In my case I used Framework64 like below

cd\
cd "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
installutil.exe "C:\XXX\Bin\ABC.exe"
pause

I think you are using the 64-bit version of the tool to install a 32-bit application. I've also faced this issue today and used this Framework path to cater .

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.


Some more detail for completeness in case it helps someone...

Note that the most common reason for this exception these days is attempting to load a 32 bit-specific (/platform:x86) DLL into a process that is 64 bit or vice versa (viz. load a 64 bit-specific (/platform:x64) DLL into a process that is 32 bit). If your platform is non-specific (/platform:AnyCpu), this won't arise (assuming no referenced dependencies are of the wrong bitness).

In other words, running:

%windir%\Microsoft.NET\Framework\v2.0.50727\installutil.exe

or:

%windir%\Microsoft.NET\Framework64\v2.0.50727\installutil.exe

will not work (substitute in other framework versions: v1.1.4322 (32-bit only, so this issue doesn't arise) and v4.0.30319 as desired in the above).

Obviously, as covered in the other answer, one will also need the .NET version number of the installutil you are running to be >= (preferably =) that of the EXE/DLL file you are running the installer of.

Finally, note that in Visual Studio 2010, the tooling will default to generating x86 binaries (rather than Any CPU as previously).

Complete details of System.BadImageFormatException (saying the only cause is mismatched bittedness is really a gross oversimplification!).

Another reason for a BadImageFormatException under an x64 installer is that in Visual Studio 2010, the default .vdproj Install Project type generates a 32-bit InstallUtilLib shim, even on an x64 system (Search for "64-bit managed custom actions throw a System.BadImageFormatException exception" on the page).


In the case of having this message in live tests, but not in unit tests, it's because selected assemblies are copied on the fly to $(SolutionDir)\.vs\$(SolutionName)\lut\0\0\x64\Debug\. But sometime few assemblies can be not selected, eg., VC++ dlls in case of interop c++/c# projects.

Post-build xcopy won't correct the problem, because the copied file will be erased by the live test engine.

The only workaround to date (28 dec 2018), is to avoid Live tests, and do everything in unit tests with the attribute [TestCategory("SkipWhenLiveUnitTesting")] applied to the test class or the test method.

This bug is seen in any Visual Studio 2017 up to 15.9.4, and needs to be addressed by the Visual Studio team.


After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.


Some more detail for completeness in case it helps someone...

Note that the most common reason for this exception these days is attempting to load a 32 bit-specific (/platform:x86) DLL into a process that is 64 bit or vice versa (viz. load a 64 bit-specific (/platform:x64) DLL into a process that is 32 bit). If your platform is non-specific (/platform:AnyCpu), this won't arise (assuming no referenced dependencies are of the wrong bitness).

In other words, running:

%windir%\Microsoft.NET\Framework\v2.0.50727\installutil.exe

or:

%windir%\Microsoft.NET\Framework64\v2.0.50727\installutil.exe

will not work (substitute in other framework versions: v1.1.4322 (32-bit only, so this issue doesn't arise) and v4.0.30319 as desired in the above).

Obviously, as covered in the other answer, one will also need the .NET version number of the installutil you are running to be >= (preferably =) that of the EXE/DLL file you are running the installer of.

Finally, note that in Visual Studio 2010, the tooling will default to generating x86 binaries (rather than Any CPU as previously).

Complete details of System.BadImageFormatException (saying the only cause is mismatched bittedness is really a gross oversimplification!).

Another reason for a BadImageFormatException under an x64 installer is that in Visual Studio 2010, the default .vdproj Install Project type generates a 32-bit InstallUtilLib shim, even on an x64 system (Search for "64-bit managed custom actions throw a System.BadImageFormatException exception" on the page).


I had the same issue. I using the standard command for execution. It was calling the X64 ro run against X86 tests. I needed to specify the X86 and not the X64 version of the nunit-runner.


I think you are using the 64-bit version of the tool to install a 32-bit application. I've also faced this issue today and used this Framework path to cater .

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.


The key is to set match processor settings for the project which are at two places.

enter image description here

And also make sure the architecture settings is same in Test menu >> Test Settings >> Default Processor Architecture >> as show below.

enter image description here

This is for VS2013 but maybe same for other versions too.

Update - For VS2019:

enter image description here


I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

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 windows-services

Can't start Tomcat as Windows Service Error 1053 the service did not respond to the start or control request in a timely fashion How to solve "The specified service has been marked for deletion" error Service will not start: error 1067: the process terminated unexpectedly How to get all Windows service names starting with a common word? Windows service with timer Windows service on Local Computer started and then stopped error Windows service start failure: Cannot start service from the command line or debugger "Automatic" vs "Automatic (Delayed start)" How to install node.js as windows service?

Examples related to x86

How to compile Tensorflow with SSE4.2 and AVX instructions? Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr) How to run a program without an operating system? Carry Flag, Auxiliary Flag and Overflow Flag in Assembly How do AX, AH, AL map onto EAX? JNZ & CMP Assembly Instructions How does the ARM architecture differ from x86? Difference between JE/JNE and JZ/JNZ

Examples related to 64-bit

Android Studio: /dev/kvm device permission denied How to printf a 64-bit integer as hex? Unable to install Android Studio in Ubuntu I cannot start SQL Server browser Class not registered Error Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required) MSOnline can't be imported on PowerShell (Connect-MsolService error) How to know installed Oracle Client is 32 bit or 64 bit? The application was unable to start correctly (0xc000007b) How to specify 64 bit integers in c

Examples related to x86-64

How to build x86 and/or x64 on Windows from command line with CMAKE? How to include static library in makefile Difference between x86, x32, and x64 architectures? Floating point vs integer calculations on modern hardware What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64 What's the purpose of the LEA instruction? How to find if a native DLL file is compiled as x64 or x86? System.BadImageFormatException: Could not load file or assembly (from installutil.exe) How can I determine if a .NET assembly was built for x86 or x64? Targeting both 32bit and 64bit with Visual Studio in same solution/project