CleverNameHere
CleverNameHere

Reputation: 49

Get location of dynamically loaded assembly

Say I have an app: C:\MyPrograms\App.exe

This app does NOT reference library.dll. App.exe can dynamically load assemblies.

And let's say that the path to the DLL is C:\MyPrograms\DLLs\library.dll

I can get the path of the executing assembly (App.exe), no matter what I've tried.

GetExecutingAssembly()

GetEntryAssembly()

AppDomain.CurrentDomain.BaseDirectory

Is there a way to get the location of a DLL that is dynamically loaded? Everything just returns, for the example, the location of App.exe

EDIT 1: Rephrasing OP...

MyApp.exe can call any DLL, via passing in the path to the DLL. This DLL can be anywhere a user drops it. Ruling out hard-coding paths or something like that.

What I would like to do is to be able to get the current location of the dynamically loaded DLL. i.e. To handle errors, I'd like to be able to write an error log to the same directory the DLL is in.

I've found and tried a handful of ways to get where the loaded DLL lives, however this either returns the directory of the CALLING assembly (MyApp.exe) or nothing at all.

Upvotes: 4

Views: 2288

Answers (2)

user1562155
user1562155

Reputation:

If you are inside the dynamically loaded assembly itself where you have defined a class called MyDynLoadObject you can do this:

Assembly assem = Assembly.GetAssembly(typeof(MyDynLoadObject));

Edit: Another way to go:

public class MyDynLoadObject
{
    public MyDynLoadObject()
    {

      Assembly assem = this.GetType().Assembly;

    }
}

Upvotes: 0

Vasyl Zvarydchuk
Vasyl Zvarydchuk

Reputation: 3839

System.Reflection.Assembly class has property Location which gets path or UNC location of the loaded file that contains the manifest. So, if for instance you load assembly in this way

var assembly = System.Reflection.Assembly.Load(@"<assembly name>");

assembly.Location will return what you ask.

Answer to Edit 1: In order to do this

to handle errors, I'd like to be able to write an error log to the same directory the DLL is in

you can

  1. Load an assembly to app domain and subscribe to AppDomain.UnhandledException where you can put error logging code. This code will know the current domain and its base directory.
  2. Pass some kind of context within assembly path while calling assembly methods and use it in logging logic. It can be thread context if you call assembly methods only in one thread.

Upvotes: 4

Related Questions