从相对路径加载c#中的dll
Loading a dll in c# from a relative path
我正在像这样在运行时加载一个 dll:
var DLL = Assembly.LoadFile(@"..\..\BuildDLLs\myDLL.dll");
我收到一个要求绝对路径的 ArgumentException。
我不想用绝对路径,我想用相对路径。
我该怎么做?
我不知道使用相对路径的方法,因此其他人可能对此有答案。但是,您可以从相对路径构建绝对路径并使用它。
// 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);
现在,如果您的程序被移动过,它仍然可以工作。
简单。多做一步:
var dllFile = new FileInfo(@"..\..\BuildDLLs\myDLL.dll");
var DLL = Assembly.LoadFile(dllFile.FullName);
我也不知道在运行时使用相对路径加载库的方法,但是如果该路径只是相对于您在用户光盘上的项目位置,但相对于您的项目具有固定位置你可以使用这样的东西:
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.*/
也许这可以帮助您解决问题,我也使用了这种 "dirty" 方法在 runtime.This 加载了一些 .dll,当然,如果您有固定的文件夹结构就可以了。
我正在像这样在运行时加载一个 dll:
var DLL = Assembly.LoadFile(@"..\..\BuildDLLs\myDLL.dll");
我收到一个要求绝对路径的 ArgumentException。
我不想用绝对路径,我想用相对路径。
我该怎么做?
我不知道使用相对路径的方法,因此其他人可能对此有答案。但是,您可以从相对路径构建绝对路径并使用它。
// 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);
现在,如果您的程序被移动过,它仍然可以工作。
简单。多做一步:
var dllFile = new FileInfo(@"..\..\BuildDLLs\myDLL.dll");
var DLL = Assembly.LoadFile(dllFile.FullName);
我也不知道在运行时使用相对路径加载库的方法,但是如果该路径只是相对于您在用户光盘上的项目位置,但相对于您的项目具有固定位置你可以使用这样的东西:
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.*/
也许这可以帮助您解决问题,我也使用了这种 "dirty" 方法在 runtime.This 加载了一些 .dll,当然,如果您有固定的文件夹结构就可以了。