Last active
October 15, 2021 08:01
-
-
Save rifatx/3ae5c94a7dfe1e785a31ca1142a2f5bf to your computer and use it in GitHub Desktop.
Get references of an .NET 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
private IEnumerable<PortableExecutableReference> GetReferences(string basePath, string assemblyName) | |
{ | |
List<string> refNames = new(); | |
List<PortableExecutableReference> references = new(); | |
Queue<AssemblyName> pending = new(); | |
var depth = 0; | |
var mainAsmName = new FileInfo(assemblyName).Name; | |
mainAsmName = mainAsmName.Substring(0, | |
mainAsmName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase)); | |
pending.Enqueue(Assembly.ReflectionOnlyLoadFrom(Path.Combine(basePath, assemblyName)).GetName()); | |
while (pending.Count > 0) | |
{ | |
var an = pending.Dequeue(); | |
if (refNames.Contains(an.Name)) | |
{ | |
continue; | |
} | |
refNames.Add(an.Name); | |
try | |
{ | |
var asm = GetAssembly(basePath, an); | |
if (asm != null) | |
{ | |
if (asm.GetName().Name != mainAsmName) | |
{ | |
references.Add(MetadataReference.CreateFromFile(asm.Location)); | |
} | |
if (depth++ < 2) | |
{ | |
foreach (var sub in asm.GetReferencedAssemblies()) | |
{ | |
pending.Enqueue(sub); | |
} | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.Error.WriteLine(ex.Message); | |
} | |
} | |
return references; | |
} | |
private Assembly GetAssembly(string basePath, AssemblyName an) | |
{ | |
if (an.Name.StartsWith("Some.Private.Namespace.")) | |
{ | |
return Assembly.ReflectionOnlyLoadFrom(Path.Combine(basePath, $"{an.Name}.dll")); | |
} | |
try | |
{ | |
return Assembly.Load(an.FullName); | |
} | |
catch | |
{ | |
return Assembly.ReflectionOnlyLoadFrom(Path.Combine(basePath, $"{an.Name}.dll")); | |
} | |
} | |
private string GetCS0012MissingAssembly(Diagnostic d) | |
{ | |
var _piDiagnosticArguments = typeof(Diagnostic).GetProperty("Arguments", (BindingFlags) 16383); | |
var arguments = (object[]) _piDiagnosticArguments.GetValue(d); | |
if (arguments != null && arguments.Length > 1) | |
{ | |
return (arguments[1] as AssemblyIdentity).GetDisplayName(); | |
} | |
return string.Empty; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment