System.BadImageFormatException when compiled using any cpu

1.2k Views Asked by At

When I compile the application using "Any CPU" I am getting System.BadImageFormatException whenever I try to open a connection using Firebird embedded dll (don't ask me why I am still using this legacy DB. not my choice)

Then I thought it must be that the dll only supports 32bit mode. So I tried to compile using x86 and indeed it runs fine this time.

However when I compile using x64 the application still runs fine. This confuses me cause it clearly indicates the dll is able to load in 64bit mode.

I made couple more tests and here are the results:

Any CPU: 64 bit process. System.BadImageFormatException
x86: 32 bit process. Runs fine
x64: 64 bit process. Runs fine
Any CPU (prefer 32bit): 32 bit process. Runs fine

I thought the only magic Any CPU does is that it picks whether to launch the process in 32/64 bit mode during startup. If the application runs fine under strict 64 bit mode then I would expect Any CPU to run fine on the same 64bit machine.

I would prefer to use Any CPU (without prefer 32bit flag) still since it makes the distribution easier.

What could be causing the exception and is there a way to deal with it?

Edit:
So I tried to use reflection to get assembly info and this is the error message I got

Exception calling "GetAssemblyName" with "1" argument(s): "Could not load file or assembly 'fbembed.dll' or one of its dependencies. The module was expected to contain an assembly manifest." At line:1 char:1 + [reflection.assemblyname]::GetAssemblyName("${pwd}\fbembed.dll") | fl + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : BadImageFormatException

1

There are 1 best solutions below

1
Steve On BEST ANSWER

After examining the dll's header it turns out that Nuget is the one performing the magic. If I set the target to x86/x64 nuget will include the according version of the dll during compile.

But if I target "Any CPU" nuget will pick the x86 version of the dll. Thus if I try to launch my application in 64 bit mode it will throw BIFE.