Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a dll in c# from a relative path

I am loading a dll at runtime like this:

var DLL = Assembly.LoadFile(@"..\..\BuildDLLs\myDLL.dll");

I am getting an ArgumentException that is asking for an absolute path.

I don't want to use an absolute path, I want to use a relative path.

How can I do that?

like image 431
whitefang1993 Avatar asked Feb 10 '16 13:02

whitefang1993


2 Answers

Simple. Make an extra step:

var dllFile = new FileInfo(@"..\..\BuildDLLs\myDLL.dll");
var DLL = Assembly.LoadFile(dllFile.FullName);
like image 139
Manuel Zelenka Avatar answered Sep 27 '22 19:09

Manuel Zelenka


I'm not aware of a way to use a relative path so someone else might have an answer for that. However you could just build an absolute path from relative paths and use that.

// Gets the folder path in which your .exe is located
var parentFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

// Makes the absolute path
var absolutePath = Path.Combine(parentFolder, "\BuildDLLs\myDLL.dll");

// Load the DLL using the absolute path
var DLL = Assembly.LoadFile(absolutePath);

Now if your program is ever moved it'll still work.

like image 42
Equalsk Avatar answered Sep 27 '22 20:09

Equalsk