Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the path of the current assembly

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.

like image 933
DenaliHardtail Avatar asked May 14 '09 16:05

DenaliHardtail


People also ask

How do I find current Assembly?

The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type. Assembly property of a type found in the assembly, as the following example illustrates. To get the assembly that contains the method that called the currently executing code, use GetCallingAssembly.

What is current Assembly in C#?

It is basically a compiled code that can be executed by the CLR. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose.

What is the method to load Assembly by name?

Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.

What is System reflection Assembly?

Namespace: System.Reflection. Summary. Defines an Assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application. C# Syntax: [Serializable]


2 Answers

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] 
like image 190
Reed Copsey Avatar answered Oct 05 '22 23:10

Reed Copsey


System.Reflection.Assembly.GetExecutingAssembly().Location

like image 31
Daniel Brückner Avatar answered Oct 05 '22 23:10

Daniel Brückner