CodeDom + Assembly.Load throws a BadImageFormatException

233 views Asked by At

I'm trying to execute a file from a given byte array, which works great:

byte[] bytes = File.ReadAllBytes(@"C:\Location\program.exe");
MessageBox.Show(bytes.Length) // The same size for both the VS compiled and CodeDom compiled application
Assembly assembly = Assembly.Load(bytes); //Throws exception when compiled with CodeDOM

This code compiles and runs fine from within an application I generated with Visual studio.

However, when I add this piece of code to an application I generated with CodeDOM, it throws a BadImageException.

The CodeDOM generated application reads the bytes fine, because both versions output the same byte[] length.

I tried changing the target framework from .NET 2.0 to .NET 4.5, I tried changing the target architecture, but I could not get it to work.

What could cause this exception?

1

There are 1 answers

0
dotnetstep On BEST ANSWER

The problem is with Assembly architecture and Application that load assembly.

So if application build with X64 and if It try to load assembly with X86 then it create problem.This apply in opposite case as well.

Other scenario is that when application build with Visual studio then default option is Any CPU.

In this case when process is 64 bit it will load as 64 bit and when application is 32 bit it is load as 32 bit. We restrict this way because some unmanaged resource works under special environment.

I encounter such problem with Oracle client of .net.