从相对路径加载dll在c#中的实现

10

我正在运行时加载一个dll,方法如下:

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

我遇到了一个ArgumentException,要求传入一个绝对路径。

但是我不想使用绝对路径,我想使用相对路径。

我该怎么做?


你需要在你的项目中引用myDLL.dll。点击这里查看详情。 - diiN__________
3个回答

13

简单,多做一步:

var dllFile = new FileInfo(@"..\..\BuildDLLs\myDLL.dll");
var DLL = Assembly.LoadFile(dllFile.FullName);

4

我不知道是否有办法使用相对路径,可能其他人有答案。但是您可以通过相对路径构建一个绝对路径并使用它。

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

现在,如果您的程序被移动,它仍将正常工作。

1
我不知道如何使用相对路径在运行时加载库,但是如果路径仅相对于用户计算机上项目位置且与您的项目有固定位置关系,则可以使用以下方法:
System.Reflection.Assembly.GetEntryAssembly().Location;
//to get the path of your main applications .exe

并且

Directory.GetParent(String)
//to move your way upwards in your folder sturcture

那么

Path.Combine(String, String)
/*to combine the path you just navigated to inside your project with the knowledge of where you can find your .dll inside of your folder sturcture and combine them into one path again.*/

也许这可以帮助您解决问题,我也使用了这种“不太正规”的方法在运行时加载一些.dll文件。当然,这仅适用于您有一个固定的文件夹结构。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接