Reputation: 28336
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.
Upvotes: 45
Views: 65199
Reputation: 7445
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"
Upvotes: 3
Reputation: 564931
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]
Upvotes: 82
Reputation: 59705
System.Reflection.
Assembly
.GetExecutingAssembly()
.Location
Upvotes: 46