How do I get the path of the assembly the code is in?
Note: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: https://docs.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.
It's as simple as this:
var dir = AppDomain.CurrentDomain.BaseDirectory;
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 );