Search code examples
c#.netdllwindows-phone

BadImageFormatException - How to reference System.IO.Compression in my Windows Phone 8.1 app?


I need to reference System.IO.Compression to use ZipArchive class in my Windows Phone Silverlight 8.1 app. I add it with Object Explorer so it copies the dll C:\Program Files\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1\System.IO.Compression.dll to my root path project, which is copied in the .xap package.

I can build but my app crashes at runtime when I reach the code that uses this library (ZipArchive instantiation). I get:

Could not load file or assembly 'System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)

with innerException

System.BadImageFormatException: Cannot load a reference assembly for execution.

My researches on BadImageFormatException (ex Troubleshooting BadImageFormatException) often say something like the dll is for 64 bits processor and it's used on 32 bits system but I don't know what is the good dll I should use for a Windows Phone.

I notice that I have another System.IO.Compression.dll in C:\Program Files\Reference Assemblies\Microsoft\Framework\WindowsPhoneApp\v8.1 but I can't import it through Visual Studio and if I copy it manually, I get the same BadImageFormatException error. In the C:\Program Files\Reference Assemblies\Microsoft\Framework\WindowsPhone\v8.1 folder, I have a System.IO.Compression.xml file, but not the dll.

Where am I wrong? How can I do work my code with this namespace?


Solution

  • Reference Assemblies typically don't contain any actual code -- they're just metadata about types (somewhat like header files in C++). So when .NET tries to use the assembly at runtime, there is no implementation.

    Consider using Microsoft.Bcl.Compression instead for compression on WP 8.