Water Cooler v2
Water Cooler v2

Reputation: 33880

Get the paths of all referenced assemblies

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?

Upvotes: 13

Views: 17761

Answers (4)

Jerther
Jerther

Reputation: 5995

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);

Upvotes: 5

Hans Passant
Hans Passant

Reputation: 942308

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.

Upvotes: 13

Stefan P.
Stefan P.

Reputation: 9519

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

Assembly.GetExecutingAssembly().GetReferencedAssemblies()[0].CodeBase

Upvotes: -1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

The CodeBase property should provide the full path name.

Upvotes: -1

Related Questions