views:

5365

answers:

3

I've got an arbitrary list of .NET assemblies.

I need to programmatically check if each DLL was built for x86. (As opposed to x64 or Any CPU.) Is this possible?

+19  A: 

You can use corflags CLI tool to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to to determine if the 32BIT flag is set to 1 (x86) or 0 (any CPU).

Here's some information about corflags.

Update: even better, you can use Module.GetPEKind to determine whether an assembly is PortableExecutableKinds value PE32Plus (64-bit), Required32Bit (32-bit and WOW), or ILOnly (any CPU) along with other attributes.

cfeduke
After seeing your update, using the GetPEKind seems to be the proper way to do this. I've marked yours as the answer.
Judah Himango
Excellent tip about Module.GetPEKind, never knew about that until now. I've always used the `corflags` tool.
Scott Dorman
GetPEKind fails in a 64 bit process when checking 32 bit assemblies
John JJ Curtis
+7  A: 

Look at System.Reflection.AssemblyName.GetAssemblyName(string assemblyFile)

You can examine assembly metadata from the returned AssemblyName instance:

[36] > [reflection.assemblyname]::GetAssemblyName(".\Microsoft.GLEE.dll") | fl

Name                  : Microsoft.GLEE
Version               : 1.0.0.0
CultureInfo           :
CodeBase              : file:///C:/projects/powershell/BuildAnalyzer/Microsoft.GLEE.dll
EscapedCodeBase       : file:///C:/projects/powershell/BuildAnalyzer/Microsoft.GLEE.dll
**ProcessorArchitecture : MSIL**
Flags                 : PublicKey
HashAlgorithm         : SHA1
VersionCompatibility  : SameMachine
KeyPair               :
FullName              : Microsoft.GLEE, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7f84f738e1fc245c

I'm using PowerShell in this example to call the method.

x0n
+7  A: 

Just for clarification, CorFlags.exe is part of the .NET Framework SDK. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:

  1. Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)

  2. CD to the directory containing the DLL in question

  3. Run corflags like this: corflags MyAssembly.dll

You will get output something like this:

    Microsoft (R) .NET Framework CorFlags Conversion Tool.  Version  3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.

Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 3
ILONLY    : 1
32BIT     : 1
Signed    : 0

The key is the "32BIT" flag as documented above: 1 = x86; 0 = Any CPU.

JoshL
Incorrect. 0 = Any CPU, not 2
Todd Brooks
My bad - thanks for pointing it out. I've updated the posting to indicate 0 for Any CPU, instead of 2.
JoshL
For x64 only the output would be (plus after 32): PE: PE32+, 32BIT : 0
Peter Mortensen