Getting the path of the current assembly

2019-01-04 02:24发布

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.

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-04 02:55

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:\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]
查看更多
看我几分像从前
3楼-- · 2019-01-04 02:56

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)

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

查看更多
我命由我不由天
4楼-- · 2019-01-04 02:58

Just to make it clear:

Assembly.GetExecutingAssembly().Location
查看更多
Evening l夕情丶
5楼-- · 2019-01-04 03:06
登录 后发表回答