我如何获得代码所在的程序集的路径?

有什么方法可以获得当前代码所在的程序集的路径吗? 我不想要调用程序集的路径,只想要包含代码的路径。

基本上我的单元测试需要读取一些xml测试文件,这些文件是相对于dll的。 我希望路径总是正确的,无论测试dll是在TestDriven.NET,MbUnit GUI或其他地方运行。

编辑。人们似乎误解了我的要求。

我的测试库位于如下位置

C:\projects\myapplication\daotests\bin\Debug\daotests.dll

而我想得到这个路径。

C:\projects\myapplication\daotests\bin\Debug\

当我从MbUnit Gui上运行时,到目前为止的三个建议都失败了。

  • Environment.CurrentDirectory(环境.当前目录)。 给出c:\Program Files\MbUnit

  • System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location。 给出C:\Documents and Settings\george\Local Settings\Temp....\DaoTests.dll

  • System.Reflection.Assembly.GetExecutingAssembly().Location得到的结果和前面一样。 得到的结果和前面的一样。

这有帮助吗?

//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 );
评论(12)

这应该是有效的,除非汇编是shadow copied

string path = System.Reflection.Assembly.GetExecutingAssembly().Location
评论(0)

你所存在的当前目录。

Environment.CurrentDirectory;  // This is the current directory of your application

如果你把.xml文件和build一起复制出来,你应该能找到它。

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));

// The location of the Assembly
assembly.Location;
评论(3)