问题描述
我需要以编程方式确定程序集是 x86、x64 还是 AnyCPU?有一个几乎相同的 问题,但它提供的解决方案
I need to determine programmatically whether an assembly is x86, x64 or AnyCPU? There is an almost identical question, but the solution that it provides
Assembly assembly = Assembly.LoadFrom(fileName);
PortableExecutableKinds peKind;
ImageFileMachine imageFileMachine;
assembly.ManifestModule.GetPEKind(out peKind, out imageFileMachine);
尝试从 32 位进程加载 64 位程序集时失败(反之亦然).
fails when trying to load a 64-bit assembly from a 32-bit process (and vice versa).
是否有一种万无一失的方式以编程方式找出程序集的编译类型?
Is there a foolproof way of programmatically finding out the compilation type of an assembly?
根据@BenVoigt 的建议,我创建了一个 小型命令行实用程序,用于检查 DLL 是否受管理以及它的 x86/x64/AnyCPU.我希望有人觉得它有用.
Based on @BenVoigt suggestion, I created a small command line utility that checks whether the DLL is managed or not and whether its x86/x64/AnyCPU. I hope someone finds it useful.
推荐答案
这个问题已经讨论过了:
This question's been covered already:
但答案不完整,建议使用Assembly.LoadFrom
.这是一个糟糕的主意,因为它会运行程序集中的代码,而且如果位数与您的进程不匹配,则会失败.
But the answers are incomplete, suggesting use of Assembly.LoadFrom
. That's a terrible idea, since it will run code from the assembly, in addition to failing if the bitness doesn't match your process.
相反,您应该使用 Assembly.ReflectionOnlyLoadFrom
.这让您无需实际加载任何代码即可读取元数据,因此架构无需正确.
Instead, you should use Assembly.ReflectionOnlyLoadFrom
. This lets you read the metadata without actually loading any code, and therefore there's no need for the architecture to be correct.
这篇关于如何以编程方式检查托管程序集是 x86、x64 还是 AnyCPU?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!