8

According to MSDN documentation,

public static Assembly LoadFrom(string assemblyFile)

throws BadImageFormatException if

assemblyFile is not a valid assembly.
-or-
Version 2.0 or later of the common language runtime is currently loaded 
and assemblyFile was compiled with a later version.

Actually, there is one extra case - loading assembly that is built for x86 from assembly that runs in x64 mode. Maybe it is included in "not a valid assembly" statement, I don't know. But this is reasonable cause of exception.

Ok, but in .NET 4.5 it doesn't! I have a .NET 4.5 WPF app, that loads different appliations for some reason. It is building for Any CPU and I'm starting it on x64 Win 7. I've been testing it on one executable, that is built for .NET 4.0 x86, and it worked fine. But when I switched my app to .NET 4.0 it began to crash on Assembly.Load method!

So, my question is, am I missing something? If not, then how did they do that - loading x86 assembly from x64 process in .NET 4.5? I'm lacking some understanding at this point.

Update

Thanks to Hans Passant, I've figured out my mistake. Actually the behavior of Assembly.Load is no different. It turned out, I didn't notice Prefer 32-bit option in project settings (or Prefer32Bit tag in .csproj file). That's why my process in .NET 4.5 ran in a 32-bit mode. This setting was true when I created WPF .NET 4.5 project. Then, when I swithced to .NET 4.0 it became inactive because there was no such an option in .NET 4.0. And when I switched back to .NET 4.5 it became false, which is so, I guess, for compatibility purpose.

4

1 回答 1

2

让我们快速清除一个假设,在安装了 .NET 4.5 的机器上不可能有不同的行为。以 4.0 为目标在运行时没有任何区别。唯一要做的就是选择一组不同的引用程序集,它们可以防止您意外使用 .NET 4.5 上可用但 .NET 4.0 上不可用的类。

无法在同一台机器上同时安装 4.0 和 4.5。.NET 4.5 不是 .NET 框架的并行版本,就像 3.5 和 4.0 是并行的。安装 4.5会替换已安装的 4.0 版本。CLR、抖动、所有运行时程序集以及 C# 编译器。

最好在这里关注您的 EXE 项目的平台目标设置,这是选择进程位数的设置。您可能犯的错误是忘记了 Debug 与 Release 版本的设置可能不同。并假设 Build + Configuration Manager 中的“活动解决方案平台”组合框有任何效果。它没有,只有项目 + 属性、构建选项卡、平台目标设置很重要。这是很多程序员都陷入的一个非常尴尬的陷阱。

于 2012-12-21T17:23:09.960 回答