Created
May 27, 2021 01:29
-
-
Save agocke/f6a80c71cc62074379e2c9c4025505b7 to your computer and use it in GitHub Desktop.
Check if assembly is a ref assembly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Reflection.Metadata; | |
using System.Reflection.PortableExecutable; | |
try | |
{ | |
using var file = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); | |
using var pe = new PEReader(file); | |
var metadataReader = pe.GetMetadataReader(); | |
bool found = false; | |
foreach (var attributeHandle in metadataReader.GetAssemblyDefinition().GetCustomAttributes()) | |
{ | |
var ctorHandle = metadataReader.GetCustomAttribute(attributeHandle).Constructor; | |
StringHandle typeNameHandle; | |
StringHandle namespaceNameHandle; | |
switch (ctorHandle.Kind) | |
{ | |
case HandleKind.MethodDefinition: | |
{ | |
var ctor = metadataReader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle); | |
var typeDef = metadataReader.GetTypeDefinition(ctor.GetDeclaringType()); | |
typeNameHandle = typeDef.Name; | |
namespaceNameHandle = typeDef.Namespace; | |
break; | |
} | |
case HandleKind.MemberReference: | |
{ | |
var ctor = metadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle); | |
var typeRef = metadataReader.GetTypeReference((TypeReferenceHandle)ctor.Parent); | |
typeNameHandle = typeRef.Name; | |
namespaceNameHandle = typeRef.Namespace; | |
break; | |
} | |
default: | |
continue; | |
} | |
if (string.Equals(metadataReader.GetString(typeNameHandle), "ReferenceAssemblyAttribute", StringComparison.Ordinal) && | |
string.Equals(metadataReader.GetString(namespaceNameHandle), "System.Runtime.CompilerServices", StringComparison.Ordinal)) | |
{ | |
found = true; | |
break; | |
} | |
} | |
Console.WriteLine(found ? "ref assembly" : "not ref assembly"); | |
} | |
catch (IOException e) | |
{ | |
Console.WriteLine("Error reading file: " + e.Message); | |
} | |
catch | |
{ | |
Console.WriteLine("Invalid managed metadata"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment