.net 获取当前程序集的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/864484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:41:50  来源:igfitidea点击:

Getting the path of the current assembly

.netvb.netvisual-studio

提问by DenaliHardtail

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).

如何获取当前程序集的路径?我需要从一些相对于当前程序集 (.dll) 位置的路径获取数据。

I thought someone told me to use the reflection namespace but I can't find anything in there.

我以为有人告诉我使用反射命名空间,但我在那里找不到任何东西。

回答by Reed Copsey

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:

评论中的一些建议是通过System.Uri.UnescapeDataString(来自vvnurmi以确保处理任何百分比编码,并使用Path.GetFullpath(来自TrueWill确保路径采用标准 Windows 形式(而不是使用斜杠而不是反斜杠) . 以下是您在每个阶段获得的示例:

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:\Temp\Temp App\bin\Debug\TempApp.EXE:

如果我们正在运行,则输出C:\Temp\Temp App\bin\Debug\TempApp.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:\Temp\Temp App\bin\Debug\TempApp.EXE]

回答by Daniel Brückner

回答by Sam Axe

Just to make it clear:

只想说清楚:

Assembly.GetExecutingAssembly().Location

回答by b_levitt

I prefer

我更喜欢

new System.Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;

EscapedCodeBase covers the scenario where your local path might have an invalid URI char in it (see https://stackoverflow.com/a/21056435/852208)

EscapedCodeBase 涵盖了本地路径中可能包含无效 URI 字符的情况(请参阅https://stackoverflow.com/a/21056435/852208

LocalPath includes the full path for both local paths and unc paths, where AbsolutePath trims off "\\server"

LocalPath 包括本地路径和 unc 路径的完整路径,其中 AbsolutePath 修剪掉“\\server”