Created
August 6, 2012 09:26
-
-
Save vbfox/3272598 to your computer and use it in GitHub Desktop.
GetReferencedAssemblies & GetDirectlyReferencedAssemblies
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
static class Utils | |
{ | |
static IEnumerable<Assembly> GetDirectlyReferencedAssemblies(Assembly startAssembly) | |
{ | |
return startAssembly.GetReferencedAssemblies() | |
.Select(TryLoad) | |
.Where(a => a != null && !a.GlobalAssemblyCache); | |
} | |
static IEnumerable<Assembly> GetReferencedAssemblies(Assembly startAssembly) | |
{ | |
var alreadyTraversed = new HashSet<Assembly>(); | |
var assembliesToTraverse = new Queue<Assembly>(); | |
assembliesToTraverse.Enqueue(startAssembly); | |
while (assembliesToTraverse.Count != 0) | |
{ | |
var assembly = assembliesToTraverse.Dequeue(); | |
if (alreadyTraversed.Contains(assembly)) | |
{ | |
continue; | |
} | |
yield return assembly; | |
alreadyTraversed.Add(assembly); | |
foreach (var referencedAssembly in assembly.GetReferencedAssemblies() | |
.Select(TryLoad) | |
.Where(a => a != null && !a.GlobalAssemblyCache && !alreadyTraversed.Contains(a))) | |
{ | |
assembliesToTraverse.Enqueue(referencedAssembly); | |
} | |
} | |
} | |
static Assembly TryLoad(AssemblyName name) | |
{ | |
try | |
{ | |
return Assembly.Load(name); | |
} | |
catch (FileNotFoundException) | |
{ | |
return null; | |
} | |
catch (FileLoadException) | |
{ | |
return null; | |
} | |
catch (BadImageFormatException) | |
{ | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment