Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
CleverNameHere Avatar asked Sep 03 '25 17:09

CleverNameHere


1 Answers

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.
like image 103
Vasyl Zv Avatar answered Sep 05 '25 05:09

Vasyl Zv