I have a dll that depends on some external files. I have relative paths (relative to the dll location) to those files.
I need to be able to load/read those files from the DLL.
To find the absolute path to the files I was using:
System.IO.Path.GetFullPath(filePath);
It seemed to be working, but I found that this is actually returning a path relative to the 'current directory'. I found that the current directory changes at some point from the dll location (and may never even be the dll path).
What's the easiest way to get the absolute path of the files relative to the DLL from code running in the DLL?
I was going to use the following, but found that it returns the path to the EXE that has loaded the DLL, not the DLL path:
AppDomain.CurrentDomain.BaseDirectory
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"
To get the full path of the dll codebase, you can use this code:
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
You can further clean this path by using a uriBuilder:
UriBuilder uri = new UriBuilder(codeBase);
string cleanFullPath = Uri.UnescapeDataString(uri.Path);
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