How to get the location of the DLL currently executing?
You are looking for System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Note:
The .Location
property returns the location of the currently running DLL file.
Under some conditions the DLL is shadow copied before execution, and the .Location
property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase
property instead.
.CodeBase
contains a prefix (file:\
), which you may need to remove.
Get DLL path at runtime
You can use the GetModuleHandleEx
function and get the handle to a static function in your DLL. You'll find more information here.
After that you can use GetModuleFileName
to get the path from the handle you just obtained. More information on that call is here.
A complete example:
char path[MAX_PATH];
HMODULE hm = NULL;
if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR) &functionInThisDll, &hm) == 0)
{
int ret = GetLastError();
fprintf(stderr, "GetModuleHandle failed, error = %d\n", ret);
// Return or however you want to handle an error.
}
if (GetModuleFileName(hm, path, sizeof(path)) == 0)
{
int ret = GetLastError();
fprintf(stderr, "GetModuleFileName failed, error = %d\n", ret);
// Return or however you want to handle an error.
}
// The path variable should now contain the full filepath for this DLL.
Get Absolute Path Relative to DLL location
GetFullPath
always assumes relative to the current directory unless you specify an absolute path. You should just manually combine your assembly path with your relative path. You can then normalize the result to get a clean path.
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string filePathRelativeToAssembly = Path.Combine(assemblyPath, @"..\SomeFolder\SomeRelativeFile.txt");
string normalizedPath = Path.GetFullPath(filePathRelativeToAssembly);
For example. If the assembly location is "C:\Test\MyAssembly.dll" then you get this
assemblyPath = "C:\Test"
filePathRelativeToAssembly = "C:\Test\..\SomeFolder\SomeRelativeFile.txt"
normalizedPath = "C:\Test\SomeFolder\SomeRelativeFile.txt"
Also, if you passed in an absolute path as the second part of Path.Combine
it will still do the proper thing.
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string filePathRelativeToAssembly = Path.Combine(assemblyPath, @"C:\AbsoluteFile.txt");
string normalizedPath = Path.GetFullPath(filePathRelativeToAssembly);
will give you
filePathRelativeToAssembly = "C:\AbsoluteFile.txt"
normalizedPath = "C:\AbsoluteFile.txt"
How do I get the path of the assembly the code is in?
Note: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0
Original answer:
I've defined the following property as we use this often in unit testing.
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
The Assembly.Location
property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use CodeBase
which gives you the path in URI format, then UriBuild.UnescapeDataString
removes the File://
at the beginning, and GetDirectoryName
changes it to the normal windows format.
Get actual dll path in .Net
You can use:
Assembly.GetExecutingAssembly().Location
which will give you the path of the executing assembly then use:
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
which will give the containing folder.
Getting the path of the current assembly
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]
C# How to get current directory path
I will answer my own question, It's not possible to get current path from library project. You'll have to get it from installer. There is no other way.
Thank you.
Related Topics
Performance of "Direct" Virtual Call VS. Interface Call in C#
C# Iterate Through Class Properties
Password Encryption/Decryption Code in .Net
Cssrewriteurltransform with or Without Virtual Directory
How to Format Datetime to Web Utc Format
Which Is Better Between a Readonly Modifier and a Private Setter
How to Await a List of Tasks Asynchronously Using Linq
How to Get Xml Node from Xdocument
C# Release Version Has Still .Pdb File
How to Convert a Datetime to the Number of Seconds Since 1970
How to Modify Existing Xml File with Xmldocument and Xmlnode in C#
How to Extend C# Built-In Types, Like String
How to Open a Serial Port by Friendly Name
Practical Usage of Virtual Functions in C#
When Should I Create a New Dbcontext()
System.Threading.Timer in C# It Seems to Be Not Working. It Runs Very Fast Every 3 Second
How to Show a Image in Database in the Image Control of ASP.NET