简体   繁体   English

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

[英]Loading a dll in c# from a relative path

I am loading a dll at runtime like this: 我在运行时加载一个dll,如下所示:

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

I am getting an ArgumentException that is asking for an absolute path. 我收到一个要求绝对路径的ArgumentException。

I don't want to use an absolute path, I want to use a relative path. 我不想使用绝对路径,我想使用相对路径。

How can I do that? 我怎样才能做到这一点?

Simple. 简单。 Make an extra step: 做一个额外的步骤:

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

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. 现在如果你的程序被移动它仍然可以工作。

I also do not know a way to use a relative path to load a library at runtime but if the path is just relative to your project location on the disc of the user but has a fixed location in relation to your project you could use something like this: 我也不知道在运行时使用相对路径加载库的方法,但如果路径只是相对于用户光盘上的项目位置,但是相对于项目有固定的位置,你可以使用像这个:

System.Reflection.Assembly.GetEntryAssembly().Location;
//to get the path of your main applications .exe

and

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

then 然后

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.*/

Maybe this helps you to solve your problem, I also used this "dirty" method to load some .dlls at runtime.This just works if you have a fixed folder sturcture of course. 也许这有助于你解决问题,我也使用这种“脏”方法在运行时加载一些.dll。如果你有一个固定的文件夹结构,这当然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM