[c#] Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I have two projects, ProjectA and ProjectB. ProjectB is a console application, which depends on ProjectA. Yesterday, everything was working fine, but suddenly today when I run ProjectB I get this:

BadImageFormatException was unhandled:
Could not load file or assembly 'ProjectA, 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.

Both are just regular projects, with no dependencies on any other non-.Net projects. Both are fully .Net - there is no native code, and no P/Invoke. I have other projects which depend on ProjectA and still work just fine.

Things I have tried:

  • Make sure both projects are set to "Any CPU," with the build checkbox checked. They are.
  • Make sure both projects are for the same Target Framework (.Net 4.0 Client Profile).
  • Under ProjectB --> References --> ProjectA --> Properties, make sure "Copy Local" is set to "True" _ (I verified that ProjectA.dll is being copied correctly)
  • Clean/Rebuild the solution. I even tried manually deleting the /bin and /obj folders in both projects.
  • Restart Visual Studio. Restart my computer.
  • Check out an entirely new copy of the repository.

But I still get the same error. I have no idea what I did to cause this, nor how to fix it. Any ideas?

The answer is


It can be a little funny, but I had the same problem with normal working code. I added StreamWriter and StreamReader and it gave that error. The solution was I took that code into comment brackets then did debug and it started to work again


First of all I got this in VS2017 with an old project I needed to make a tiny change to and upraded all the projects to framework 4.7.


Several others have mentioned selecting Any CPU can fix this issue.

There's a couple places you need to do it, and it might not just be as simple as selecting from the dropdown. This fixed it for me:

1) You need to do it both here:

enter image description here

2) And also in Configuration Manager (right click on solution)

enter image description here

But what if it isn't there???

Then click New and choose these settings: (thanks @RckLN)

enter image description here


I had the same issue with multiple projects in the same solution, i ended up setting all of the target frameworks to .NET Framework 4 and x86 for the target CPU and it finally successfully compiled.


I also had this problem running unit tests by using ReSharper on Visual Studio 2017 and fixed it with following config:

enter image description here

Also you can change the ReSharper's run test setting: https://resharper-support.jetbrains.com/hc/en-us/articles/207242715-How-to-run-MSTest-tests-using-x64-configuration


The Chilkat .NET 4.5 assembly requires the VC++ 2012 or 2013 runtime to be installed on any computer where your application runs. Most computers will already have it installed. Your development computer will have it because Visual Studio has been installed. However, if deploying to a computer where the required VC++ runtime is not available, the above error will occur:

Install all of the bellow packages

Visual C++ Redistributable Packages for Visual Studio 2013 - vcredist_x64

Visual C++ Redistributable Packages for Visual Studio 2013 - vcredist_x86

Visual C++ Redistributable Packages for Visual Studio 2012 - vcredist_x64

Visual C++ Redistributable Packages for Visual Studio 2012 - vcredist_x86


In my project for C#, project property->[Build]->Platform target: Any CPU, and uncheck the Prefer 32-bit to let compiler to choose automatically.


I had the same issue. Project B in my case was a .Net Core Class Library which has a Nuget "Microsoft.Management.Infrastructure" installed. The error was that i called my project B "MI". I changed the project name to something else and suddenly everything worked again.


My machine showed me a BIOS update and I wondered if that has something to do with the sudden popping-up of this error. And after I did the update, the error was resolved and the solution built fine.


I have detected something different from the other answers. Reaching this exception in my project was the result of a corrupt compilation. Without making any changes, just forcing rebuild, it was fixed.


I encountered the same issue. It popped up out of the blue and that seemed strange to me.

In the Exception snapshot, for the FusionLog, I saw the following within its message:

... C:\Windows\Microsoft.NET\Framework64 ...

More about the fusion log: http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.110).aspx

All the projects had a Target CPU of AnyCPU. I changed the application project (the project that references all the other projects) to a Target CPU of x86. It now works.

Not sure how the Target CPU mix up occurred for no apparent reason, but it did.


Might be you are facing the problem with your website after deploying on server.

Then you need to adjust your application pool to Enable 32-Bit Applications.

Steps

  1. Open IIS Manager
  2. Click on Application Pools
  3. Select whatever application pool you are using
  4. From right pane, click Advanced Settings...

  5. Set Enable 32-Bit Applications to True

    Advanced Settings Enable 32-Bit


Shoot! I knew about this problem. I thought I was doing everything right until I accidentally saw 'x86' in the VS output window and that's when I got hold of the cause. Wasted a few mins on it today.

The configuration under 'Publish' window was set to 'x86'; whereas, everywhere else, it was 'x64'.

Please make sure it's in-sync across configuration manager, publish settings, solution configurations, and IIS settings (if that's your web server).

Also, please keep in mind - VS is a 32-bit app and IIS is 64 bit. 32-bit apps are disabled by default in IIS.

enter image description here


I just had this error message running IIS Express in Visual Studio 2015. In my case I needed to be running the 64 bit version of IIS Express:

Tools ? Options ? Projects and Solutions ? Web Projects
Check the box that says "Use the 64 bit version of IIS Express for web sites and projects".

Screenshot:

Screenshot of VS options for Web Project.


I had this same problem. I had set Project A's "Platform Target" ("Project A"(Right Click)->Properties->Build->"Platform Target") to x86 but kept Project B's at "Any CPU". Setting Project B's to "x86" fixed this.


I also face this problem in a project, after a few minutes i found the solution, this problem is due to CPU configuration, If you are using Visual Studio 2010 or VS 2013, just goto project 's properties and then select Compile from side bar and there will be 5 drop-down, 5th Drop-down will be Target CPU:, you should set it to x86 or x64 according to your requirements instead of Any CPU.

My problem was solved after changing it to x86.


In my case the error was System.BadImageFormatException: Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

It was solved by installing vjredist 64 from here.


None of these solutions worked for me - but by deleting the contents of bin and obj folders everything was cool again.


You might also see this issue if you're trying to package a 64bit project with an MSI installer in VS. ("The reason is because the native shim packaged with the .msi file is a 32-bit executable.")

See here for more details: http://blogs.msdn.com/b/heaths/archive/2006/02/01/64-bit-managed-custom-actions-with-visual-studio.aspx


I got this when building a project via Visual Studio Online (VSTS) Build using Visual Studio Build Steps.

The solution was:

  • Delete the existing source folder
  • Explicitly set 'Any CPU' in the platform for all Visual Studio Builds including dependencies (see screenshot below).
  • Re-run the build

VSO Screenshot


In my case a dependency was missing in the dll that threw this exception. I checked with Dependency Walker, added the missing dll and the problem was resolved.

More specifically, I somehow corrupted my opencv_core340.dll by accidentally adding SVN keywords to it, and thus my dll could no longer use it. However I don't believe that the solution to this problem depends on whether the dll is corrupted or missing. I'm just adding this for the sake of giving complete information.


If you use LibreOffice from your program via cli .net integration like me, I got the same error. I use the older version of LibreOffice on the production environment on my PC I installed a newer version that was in conflict. Just uninstall LibreOffice. I found the solution here .NET CLI: Could not load file or assembly 'cli_cppuhelper'


You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.


Are you trying to run your .exe file from the cmd? This was my mistake. Just run the .exe file by double clicking it. If it's a .NET Core SCD for Windows 8.1/Windows Server 2012 R2 x64.


This also can happen just by having multiple supported frameworks defined in the app.config file and, forcing the app to run in a different .NET framework other than the one mentioned first in the app.config file.

And also this fires when you have both of the mentioned frameworks available in your system.

As a workaround, bring up the target framework you are going to use for the debugging up in the app.config

ex: if you trying to run in .NET 4, config file should have something similar to this,

<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>

The following solved the issue for me, uncheck 'Prefer 32-bit' : enter image description here


I had this problem running unit tests (xunit) in Visual Studio 2015 and came across the following fix:

Menu Bar -> Test -> Test Settings -> Default Processor Architecture -> X64

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

Examples related to console-application

How to run .NET Core console app from the command line ASP.NET Core configuration for .NET Core console application How to keep console window open How to navigate a few folders up? How to stop C# console applications from closing automatically? Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException) Can I write into the console in a unit test? If yes, why doesn't the console window open? What is the command to exit a Console application in C#? Can't specify the 'async' modifier on the 'Main' method of a console app Why is the console window closing immediately once displayed my output?

Examples related to badimageformatexception

The module was expected to contain an assembly manifest Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException) System.BadImageFormatException An attempt was made to load a program with an incorrect format "An attempt was made to load a program with an incorrect format" even when the platforms are the same