Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.
<Same as John's answer, but a slightly less verbose extension method.
public static string GetDirectoryPath(this Assembly assembly)
{
string filePath = new Uri(assembly.CodeBase).LocalPath;
return Path.GetDirectoryName(filePath);
}
Now you can do:
var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();
or if you prefer:
var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();
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.
The only solution that worked for me when using CodeBase and UNC Network shares was:
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
It also works with normal URIs too.
I believe this would work for any kind of application:
AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory
What about this:
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
I got the same behaviour in the NUnit
in the past. By default NUnit
copies your assembly into the temp directory. You can change this behaviour in the NUnit
settings:
Maybe TestDriven.NET
and MbUnit
GUI have the same settings.