1.通过读取PE头信息判断
public static bool IsManagedAssembly(string filePath) {
if (!File.Exists(filePath))
throw new FileNotFoundException("The file does not exist.", filePath);
using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using var peReader = new PEReader(fs);
if (peReader.HasMetadata) {
var reader = peReader.GetMetadataReader();
return reader.IsAssembly;
}
return false;
}
2.通过读取 AssemblyName 判断
public static bool IsNetAssembly(string dllPath) {
if (!File.Exists(dllPath)) {
throw new FileNotFoundException("DLL not found.", dllPath);
}
try {
AssemblyName name = AssemblyName.GetAssemblyName(dllPath);
// .NET程序集通常包含一个CLR头,可以通过检查这个属性来判断
return name.Flags == AssemblyNameFlags.None;
}
catch (BadImageFormatException) {
// 如果抛出BadImageFormatException异常,则不是.NET程序集
return false;
}
}