如何获取代码所在程序集的路径? [英] 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.
基本上我的单元测试需要读取一些与 dll 相关的 xml 测试文件.无论测试 dll 是从 TestDriven.NET、MbUnit GUI 还是其他东西运行,我都希望该路径始终正确解析.
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.
我的测试库位于
C:projectsmyapplicationdaotestsinDebugdaotests.dll
C:projectsmyapplicationdaotestsinDebugdaotests.dll
我想得到这个路径:
C:projectsmyapplicationdaotestsinDebug
C:projectsmyapplicationdaotestsinDebug
当我从 MbUnit Gui 运行时,到目前为止的三个建议让我失望:
The three suggestions so far fail me when I run from the MbUnit Gui:
Environment.CurrentDirectory
给出 c:Program FilesMbUnit
System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location
给 C:Documents 和设置乔治本地SettingsTemp ....DaoTests.dll
System.Reflection.Assembly.GetExecutingAssembly().Location
给出和前面一样的.
推荐答案
我定义了以下属性,因为我们在单元测试中经常使用它.
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);
}
}
Assembly.Location
属性在使用 NUnit(其中程序集从临时文件夹运行)时有时会给你一些有趣的结果,所以我更喜欢使用 CodeBase
它给你URI格式的路径,然后UriBuild.UnescapeDataString
去掉开头的File://
,GetDirectoryName
改成普通的windows格式.
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屋!