简体   繁体   中英

CodeDom + Assembly.Load throws a BadImageFormatException

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM