Problem
Is there a method to find out where the current code is located in the assembly? I only need the route to the code, not the path to the calling assembly.
My unit test only needs to read certain xml test files that are related to the dll. Whether the testing dll is run from TestDriven.NET, the MbUnit GUI, or wherever else, I want the path to always resolve correctly.
Edit: It appears that some people are misinterpreting what I’m asking.
My test library is in, let’s say,
and I’d prefer to go this route:
When I run away from the MbUnit GUI, the three suggestions so far have failed me:
Asked by George Mauer
Solution #1
Because we use this attribute frequently in unit testing, I’ve specified it.
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);
}
}
When using NUnit (where assemblies run from a temporary folder), the Assembly.Location property can produce some strange results, thus I prefer to use CodeBase, which gives you the path in URI format, followed by UriBuild. GetDirectoryName converts it to the standard Windows format, whereas UnescapeDataString eliminates the File:/ at the start.
Answered by John Sibly
Solution #2
It’s as straightforward as this:
var dir = AppDomain.CurrentDomain.BaseDirectory;
Answered by Jalal El-Shaer
Solution #3
Does this help?
//get the full location of the assembly with DaoTests in it
string fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;
//get the folder that's in
string theDirectory = Path.GetDirectoryName( fullPath );
Answered by Keith
Solution #4
Similar to John’s response, but with a less verbose extension approach.
public static string GetDirectoryPath(this Assembly assembly)
{
string filePath = new Uri(assembly.CodeBase).LocalPath;
return Path.GetDirectoryName(filePath);
}
You can now accomplish the following:
var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();
Alternatively, if you prefer:
var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();
Answered by Sneal
Solution #5
When utilizing CodeBase and UNC Network shares, the following was the only approach that worked for me:
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
It also works with standard URIs.
Answered by Ignacio Soler Garcia
Post is based on https://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in