13

How do I get the paths of all the assemblies referenced by the currently executing assembly? GetReferencedAssmblies() gives me the AssemblyName[]s. How do I get to where they are loaded from, from there?

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • 4
    Try this http://stackoverflow.com/questions/1582510/get-pathes-of-assemblies-used-in-type – Jason Evans Nov 16 '10 at 11:16
  • For a fully working example of how to get all referenced assemblies, recursively, see http://stackoverflow.com/questions/383686/how-do-you-loop-through-currently-loaded-assemblies/26300241#26300241. – Contango Oct 10 '14 at 13:33

4 Answers4

13

You cannot know until the assembly is loaded. The assembly resolution algorithm is complicated and you can't reliably guess up front what it will do. Calling the Assembly.Load(AssemblyName) override will get you a reference to the assembly, and its Location property tells you what you need.

However, you really don't want to load assemblies up front, before the JIT compiler does it. It is inefficient and the likelihood of problems is not zero. You could for example fire an AppDomain.AssemblyResolve event before the program is ready to respond to it. Avoid asking this question.

Mike Nitchie
  • 1,166
  • 2
  • 13
  • 29
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
5

Following Hans Passant's answer, and since the CodeBase property always contained null, I came up with this. It might not find all assemblies since they might not all be already loaded. In my situation, I had to find all reference of a previously loaded assembly, so it worked well:

IEnumerable<string> GetAssemblyFiles(Assembly assembly)
{
    var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
    return assembly.GetReferencedAssemblies()
        .Select(name => loadedAssemblies.SingleOrDefault(a => a.FullName == name.FullName)?.Location)
        .Where(l => l != null);
}

Usage:

var assemblyFiles = GetAssemblyFiles(typeof(MyClass).Assembly);
Jerther
  • 5,558
  • 8
  • 40
  • 59
-1

The CodeBase property should provide the full path name.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
-1

You can get the URL location of the assembly like this:

Assembly.GetExecutingAssembly().GetReferencedAssemblies()[0].CodeBase
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
  • 2
    CodeBase returns null. The solution is in the post that JasonEvans linked to in his comment to the original post. Also, Hans Passant has the right answer, too. – Water Cooler v2 Nov 16 '10 at 12:13