question

NicholasPiazza-0093 avatar image
0 Votes"
NicholasPiazza-0093 asked NicholasPiazza-0093 answered

How to fix System.BadImageFormatException

I have a project with a method that uses a DLL from another project. It used to work just fine, but now when I try to execute that method, I get the exception:

System.BadImageFormatException: 'Could not load file or assembly 'MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (0x80131058)'

The project file looks like this:
<Project Sdk="Microsft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<LangVersion>9.0</LangVersion>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="MyLibrary">
<HintPath>....\MyLibrary\MyLibrary\obj\Debug\net5.0\ref\MyLibrary.dll</HintPath>
</Reference>
</ItemGroup>

</Project>

How do I fix this problem?

dotnet-csharp
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BadImageFormatException is usually due to bitness. One project is 64 bit and the the other is 32 bit. Make sure both project target the same bitness x86 or 64.

1 Vote 1 ·

Targeted both projects for x64; same problem. Then targeted both projects for x86; same problem. The strange this is that both projects worked just last week targeted for AnyCpu. Just yesterday, I installed a Windows Quality Update (2021-09 Cumulative Update for windows 10 Version 21H1 for x64-based Systems (KB5005565). Do you think that could have something to do with this problem?

0 Votes 0 ·

1 Answer

NicholasPiazza-0093 avatar image
1 Vote"
NicholasPiazza-0093 answered

OK, Solved the problem. Was using the DLL from .net5.0\ref. Changed to using the DLL from .net5.0 folder. Thanks for the help.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.