How do I get the path of the assembly the code is in?
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.
Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.
Edit : People seem to be misunderstanding what I'm asking.
My test library is located in say
C:projectsmyapplicationdaotestsbinDebugdaotests.dll
and I would like to get this path:
C:projectsmyapplicationdaotestsbinDebug
The three suggestions so far fail me when I run from the MbUnit Gui:
Environment.CurrentDirectory
gives c:Program FilesMbUnit
System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location
gives C:Documents and SettingsgeorgeLocal SettingsTemp ....DaoTests.dll
System.Reflection.Assembly.GetExecutingAssembly().Location
gives the same as the previous.
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.
这有帮助吗?
//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 );
这很简单:
var dir = AppDomain.CurrentDomain.BaseDirectory;
链接地址: http://www.djcxy.com/p/3574.html
上一篇: 创建通用方法约束T到一个枚举
下一篇: 我如何获得代码所在的程序集路径?