Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Absolute Path Relative to DLL location

Tags:

c#

path

dll

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
like image 300
George Hernando Avatar asked Jan 05 '15 18:01

George Hernando


2 Answers

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"
like image 149
Ben Randall Avatar answered Nov 11 '22 18:11

Ben Randall


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);
like image 24
Tim Eeckhaut Avatar answered Nov 11 '22 20:11

Tim Eeckhaut