获取当前程序集的路径 [英] Getting the path of the current assembly
问题描述
如何获取当前程序集的路径?我需要从一些相对于当前程序集 (.dll) 位置的路径获取数据.
我以为有人告诉我使用反射命名空间,但我在那里找不到任何东西.
您可以使用:
string path = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
评论中的一些建议是通过 System.Uri.UnescapeDataString
(来自 vvnurmi) 以确保处理任何百分比编码,并使用 Path.GetFullpath
(来自 TrueWill) 以确保path 是标准的 Windows 形式(而不是斜线而不是反斜线).以下是您在每个阶段获得的示例:
string s = Assembly.GetExecutingAssembly().CodeBase;Console.WriteLine("代码库:[" + s + "]");s = (new Uri(s)).AbsolutePath;Console.WriteLine("绝对路径:[" + s + "]");s = Uri.UnescapeDataString(s);Console.WriteLine("未转义:[" + s + "]");s = Path.GetFullPath(s);Console.WriteLine("全路径:[" + s + "]");
如果我们运行的是输出 C:TempTemp AppinDebugTempApp.EXE
:
How do I get the path of the current assembly? I need to get data from some paths relative to the location of hte current assembly (.dll).
I thought someone told me to use the reflection namespace but I can't find anything in there.
You can use:
string path = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
Some suggestions in the comments are to pass that through System.Uri.UnescapeDataString
(from vvnurmi) to ensure that any percent-encoding is handled, and to use Path.GetFullpath
(from TrueWill) to ensure that the path is in standard Windows form (rather than having slashes instead of backslashes). Here's an example of what you get at each stage:
string s = Assembly.GetExecutingAssembly().CodeBase;
Console.WriteLine("CodeBase: [" + s + "]");
s = (new Uri(s)).AbsolutePath;
Console.WriteLine("AbsolutePath: [" + s + "]");
s = Uri.UnescapeDataString(s);
Console.WriteLine("Unescaped: [" + s + "]");
s = Path.GetFullPath(s);
Console.WriteLine("FullPath: [" + s + "]");
Output if we're running C:TempTemp AppinDebugTempApp.EXE
:
CodeBase: [file:///C:/Temp/Temp App/bin/Debug/TempApp.EXE] AbsolutePath: [C:/Temp/Temp%20App/bin/Debug/TempApp.EXE] Unescaped: [C:/Temp/Temp App/bin/Debug/TempApp.EXE] FullPath: [C:TempTemp AppinDebugTempApp.EXE]
这篇关于获取当前程序集的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!