发现(无需访问源项目).NET 程序集 DLL 是否被编译为“x86”、“x64”或“任何 CPU”的最简单方法是什么?
更新:命令行实用程序足以满足我的即时需求,但只是为了完整起见,如果有人想告诉我如何以编程方式进行操作,那我肯定也会感兴趣。
发现(无需访问源项目).NET 程序集 DLL 是否被编译为“x86”、“x64”或“任何 CPU”的最简单方法是什么?
更新:命令行实用程序足以满足我的即时需求,但只是为了完整起见,如果有人想告诉我如何以编程方式进行操作,那我肯定也会感兴趣。
如果您只想在给定的 dll 上找到它,那么您可以使用 Windows SDK 中的CorFlags工具:
CorFlags.exe assembly.dll
如果您想使用代码来完成,请查看Module类的GetPEKind方法:
Assembly assembly = Assembly.LoadFrom("path to dll");
PortableExecutableKinds peKind;
ImageFileMachine imageFileMachine;
assembly.ManifestModule.GetPEKind(out peKind, out imageFileMachine)
然后您需要检查peKind
以检查其值。有关详细信息,请参阅MSDN 文档PortableExecutableKinds
。
谢谢阿德里安!我已经在 PowerShell 中重写了代码片段,因此我可以在服务器上使用它。
#USAGE #1
# Get-Bitness (dir *.dll | select -first 1)
#USAGE #2
# Get-Bitness "C:\vs\projects\bestprojectever\bin\debug\mysweetproj.dll"
function Get-Bitness([System.IO.FileInfo]$assemblyFile)
{
$peKinds = new-object Reflection.PortableExecutableKinds
$imageFileMachine = new-object Reflection.ImageFileMachine
$a = [Reflection.Assembly]::LoadFile($assemblyFile.Fullname)
$a.ManifestModule.GetPEKind([ref]$peKinds, [ref]$imageFileMachine)
return $peKinds
}
谢谢阿德里安和彼得!这是 Peter 的 Get-Bitness 的修改版本,它 1) 从管道中获取要检查的文件列表,并且 2) 如果查看非 .NET DLL(例如,如果它查看某些 C++ DLL),它不会死掉:
# example usage: dir *.exe,*.dll | Get-PEKind
function Get-PEKind {
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[System.IO.FileInfo]$assemblies
)
Process {
foreach ($assembly in $assemblies) {
$peKinds = new-object Reflection.PortableExecutableKinds
$imageFileMachine = new-object Reflection.ImageFileMachine
try
{
$a = [Reflection.Assembly]::LoadFile($assembly.Fullname)
$a.ManifestModule.GetPEKind([ref]$peKinds, [ref]$imageFileMachine)
}
catch [System.BadImageFormatException]
{
$peKinds = [System.Reflection.PortableExecutableKinds]"NotAPortableExecutableImage"
}
$o = New-Object System.Object
$o | Add-Member -type NoteProperty -name File -value $assembly
$o | Add-Member -type NoteProperty -name PEKind -value $peKinds
Write-Output $o
}
}
}
我是 PowerShell 的新手,因此这可能不是最佳实践的示例。
或者,根据https://stackoverflow.com/a/4719567/64257,PowerShell社区扩展中可能还有一个方便的 Get-PEHeader cmdlet 。
C# 片段,基于 Powershell 答案:
var modules = assembly.GetModules();
var kinds = new List<PortableExecutableKinds>();
var images = new List<ImageFileMachine>();
foreach (var module in modules)
{
PortableExecutableKinds peKinds;
ImageFileMachine imageFileMachine;
module.GetPEKind(out peKinds, out imageFileMachine);
kinds.Add(peKinds);
images.Add(imageFileMachine);
}
var distinctKinds = kinds.Distinct().ToList();
var distinctImages = images.Distinct().ToList();