Getting the path to the current assembly

How do I get the path to the current assembly? I need to get data from some paths relative to the location of the hte current assembly (.dll).

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

+42
visual-studio
May 14 '09 at 16:52
source share
4 answers

You can use:

string path = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath; 

Some suggestions in the comments should go through System.Uri.UnescapeDataString (from vvnurmi ) to provide any percentage processing, and use Path.GetFullpath (from TrueWill ) to make sure the path is in the standard Windows form (instead of having oblique traits instead of backslashes). Here is 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 + "]"); 

Conclusion, if we execute 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]
+71
May 14 '09 at 16:55
source share
โ€” -
+43
May 14 '09 at 16:57
source share

Just to make it clear:

 Assembly.GetExecutingAssembly().Location 
+6
May 14 '09 at 18:41
source share

I prefer

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

EscapedCodeBase covers a scenario in which your local path may have an invalid char URI in it (see https://stackoverflow.com/a/16727/ ... )

LocalPath includes the full path for both local paths and non-empty paths, where AbsolutePath disables "\\ server"

+1
Jul 07 '15 at 20:50
source share



All Articles