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.
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.
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.
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.
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]
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]
System.Reflection.
Assembly
.GetExecutingAssembly()
.Location
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With