System.BadImageFormatException was unhandled - simple fix - c#

Here is a short video of my error.
It is obvious that I have something wrong between 32-bit and 64-bit. However I cant find anything that holds my hand enough to walk through the solution in Visual Studio 2012.
Can anyone give me a more detailed explanation of what and how to change in my settings?

The "startup project" (the one that builds the .exe file) determines whether the process will run 32 or 64 bits. Any library that is referenced must support the same "bitness".
If you use libraries that requires a specific CPU type, you should change the "Target CPU" property in the "Build" tab of the project properties of the project that creates the main executable to that CPU type.
Any managed library that you use, that does not depend on cpu-specific libraries can be compiled as "Any CPU".
I don't know the library you're using, but this link makes me think it requires a 32 bit build.
EDIT: I just realized I only know earlier versions of Visual Studio, so the option may be located elsewhere in 2012.

I've dealt with a similar issue just a few days ago. It wasn't as straightforward as one would expect (given the error), I had to use dependency walker in order to check if all needed dependencies of my dlls were in the correct format, turned out my dll was importing an incorrect dependency.
Dependency Walker

Related

Deterministic build is not really deterministic in .NET 6

I set <Deterministic> to true in my .csproj file as specified in the docs to create deterministic outputs.
I need any team member on any machine to be able to create the exactly same DLL when builds our project.
However, when I build, and compare my DLL files to my teammate's DLL files, I see that some files are different.
How can I debug this? How can I find out where the problem might be?
We have the same versions of .NET SDK and Visual Studio. We have the same versions of Windows. Almost everything is the same.
I want to know how can I troubleshoot this problem. Thank you.

C#.net DLL COM wrapper and installation

I'm making a load of code bits that will eventually be used in another C# program long term, but I may want to use it in various other apps, and I need to use it easily now as it gradually develops. So I've written a few C#.net DLLs in Visual Studio Express 2017. Two of which reference a 3rd-party DLL (one of which was installed by other software, one of which I just pointed at in Visual Studio), and one of my DLLs references my other 2 DLLs. I've ticked the boxes to COM register my ones and I'm now happily using them from Excel/VBA.
But how do I install it on another Win10 machine in simple steps though, so I can use the same spreadsheets and automation on those computers? (preferably with some explanation of what the steps are actually doing?) I haven't had any luck with the other options I've googled, maybe they're not "idiot proof" enough for me, or my DLLs have dependencies on other DLLs, or I'm getting them from the wrong place.
I assume these are 64-bit DLLs (they're complied for 'Any CPU') so I
want to copy them into the 64-bit place (syswow64)? Or should they go
in system32 as well?
I guess I get them from my 'release', not 'debug' folders?
I also have .pdb and .tlb as well as .dll. Do I need these? Maybe they're the missing piece of the jigsaw?
What's the difference between regsvr and regasm and what should I be using? (Or both).
Also is there a simple way to make a DLL copying and COM registering installer app? And if yes, does that still apply if it's VS Express
2017?
Thanks for the help!

ConfuserEx obfuscated DLL crashes VS 2017 when referenced

I've used ConfuserEx to obfuscate the code of my DLL but if I use anything other than the minimum level of obfuscation, the DLL crashes Visual studio 2017 a few seconds after I add a reference to it with a 'bad image' exception. The same DLL will however work fine in VS 2013. I want to use the maximum level of obfuscation to protect my code so is there a work around for this? I have searched on Google but have not found a concrete solution to this problem, although others seem to have experienced it. Perhaps there is a setting in VS 2017 that will allow me to use the fully obfuscated DLL without crashing?
Usually a bad image format exception...I am assuming...means that the .dll might not be compiled for AnyCpu and you are loading it into a project that is compiled differently. Example: dll was compiled for X86 but your project is compiling to X64. Not sure if that helps.

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?
I am pretty sure you're having a 32-bit / 64-bit conflict. It sounds like your main project might be set to 32-bit while the class its referencing is set to 64-bit. Try looking at this SO question and this one too. Between the two of them, you should be able to figure out your problem.
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
Open IIS Manager
Click on Application Pools
Select whatever application pool you are using
From right pane, click Advanced Settings...
Set Enable 32-Bit Applications to True
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:
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 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
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.
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:
2) And also in Configuration Manager (right click on solution)
But what if it isn't there???
Then click New and choose these settings: (thanks #RckLN)
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.
None of these solutions worked for me - but by deleting the contents of bin and obj folders everything was cool again.
The following solved the issue for me, uncheck 'Prefer
32-bit' :
For the newer version of visual studio (v16.10 for this answer), it can be fixed by manually changing the solution platform. For me it worked after changing from "Any CPU" to "x86".
Click on solutions platform dropdown, the one in which any CPU is appearing in image below.
Go to configuration manager.
Click on new and add platform x86 or x64 (32 or 64 bits) based on what is working for you.
Restart the project.
I also had this problem. As mention before the problem was related to a 32-bit / 64-bit conflict, but with the site hosted in Azure. To change the plattform in Azure App Service, go to Configuration -> General settings.
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
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 case changing IIS Express Bitness from "Default" to "x86" helped.
All my projects had "x86" as the Platform target.
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 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.
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.
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"/>
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 also had this problem running unit tests by using ReSharper on Visual Studio 2017 and fixed it with following config:
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
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.
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
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'
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.
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 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.
Interesting as it goes, this can also happen if the folder path is long, which can cause build issues, oddly enough with this cryptic error message.
Just moving the folder up the path, solved the problem!
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.
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.

Stand-alone build system for Visual Studio projects

We use Make to compile our product, which includes, C, C++, Java and a bunch of other bits and pieces. As much as possible we have all tools required to compile the whole thing checked into source control, to eliminate local dependencies and to ensure consistency across dev machines.
Recently we've added some components written in C# using Visual Studio and would like to take a similar approach with Visual Studio solutions. Shelling out to devenv isn't a good option. Calling csc.exe directly (as I've done before using Nant) would require keeping track of file dependencies in the build script, which I'd rather just let the Visual Studio solution do.
MSBuild seems like a good bet, though its default location in %windir%\Microsoft.NET\Framework\[version]\ makes me worried about variability between machines, both with the [version] in the path and the fact that you'll see both "Framework" and "Framework64" directories. I wouldn't mind having a requirement that all developers have whatever .NET framework version installed, but I do worry that your v3.5 might not be the same as mine.
Does anyone have a solution to this that they like? Tried anything that you really didn't like?
MSBuild is the lowest-friction option for sure. Different fx versions aren't that big a deal at build-time- if you're using something important from a fx version higher than what's installed, it won't build. The last place I was at, we built a huge multi-environment build system with NAnt as the base, and it hooked out to MSBuild with NAnt's MSBuild tasks. MSBuild is fine on its own if you're just doing MS stuff, but we had a bunch of things that MSBuild didn't natively support, hence the NAnt wrapper.
I agree with everyone else. To make it easy, just make vsvars.bat (the batch file that is the Visual Studio Command prompt) part of your build script, and then MSBuild will just work.
We use Nant to drive msbuild. If you're worried about different versions of the framework, particularly service packs, use FxCop to check that you're not letting unexpected dependencies creep in. Details are in this answer.
MSBuild is the right tool for this job. Just match your framework version to the version of the framework bundled with the Visual Studio you're using.
32-bit versus 64-bit shouldn't matter, I don't think -- I'm pretty sure both the 32-bit and 64-bit editions of Csc.exe can cross-compile to the other platform. The MSBuild project file (*.*proj XML file) should contain everything MSBuild needs to build your application.

Categories