Friday, August 23, 2013

Troubleshooting System.BadImageFormatException - Changing Target platform - A hack that might work

Introduction

Often times, we run to case where we are trying to load a dll from third party vendor that is not matching our development configuration. 
For example, we might have a .NET 4.5 solution or project that is trying to load a third party library in form of a .dll file but run into System.BadImage.FormatException error.

According to MSDN there might be any number of reason for this error. The details are listed on the following link:

But I found another solution which is not listed anywhere on MSDN and sites that I googled.

Details

Here is the scenario. I had a project that was written in .NET 4.5. I was trying to reference a library that was specific to .NET 64x platform. I added the reference to the library and complied the project. The compilation was successful. So far so good. But when I ran the application I was getting the following error:

System.BadImageFormatException
"Could not load file or assembly 'blahblah.x64, Version=x.x.xxx.xxx, Culture=neutral, PublicKeyToken=xxxxxxxxxxx' or one of its dependencies. An attempt was made to load a program with an incorrect format."

I did a lot of research and found that one reason might the mismatch in the target .NET framework. My assumption was that I might have a library that is written in .NET 2.0. 
So, the solution that I found was that I changed the target framework of my solution to .NET 2.0. I ran the application the loading of the dll worked fine. But some part of my application that were using features in .NET 4.5 stared to break. So it was a catch 22 kind of scenario. So what I did is that by pure luck I switched back my platform to 4.5 and ran the application. This time I did not get the terrible error that I mentioned above.

That seemed odd. So I created a brand new application using .NET 4.5 as framework and repeated the steps mentioned above. On adding the library for the first time and running the application, I got the error. Then I switch the framework to .NET 2.0 and rebuild the solution and ran the application and it worked. I then swithched back my solution to .NET 4.5 and this time no error. 

I do not exactly know why it starts working after switching the framework a couple of times. My guess is that when we switch framework from .NET 2.0 to .NET 4.5, I think there is a kind of upgrade that Visual Studio is doing that fixes the error.

Conclusion

If you get in similar situation where you cannot figure out the fix for the BadImageFormatException and have tried all different kinds of solution and it does not seem to work then you might try the solution that I have mentioned in the details section. That might work.