Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check programmatically whether a managed assembly is x86, x64 or 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);

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?

EDIT: 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.

like image 985
AngryHacker Avatar asked Feb 27 '12 18:02

AngryHacker


2 Answers

This question's been covered already:

  • How to Tell if a .NET Assembly Was Compiled as x86, x64 or Any CPU
  • How to determine if a .NET assembly was built for x86 or x64?
  • How can I get the processor architecture of an assembly dll?

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.

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.

like image 156
Ben Voigt Avatar answered Oct 21 '22 02:10

Ben Voigt


Solution how to determinate this just by code without reflection nor thirdparty SW can be found here: How to determine if a .NET assembly was built with platform target AnyCPU, AnyCPU Prefer32-bit, x86, x64 without using reflection and third party SW

like image 25
user2126375 Avatar answered Oct 21 '22 01:10

user2126375