我如何获得大会的code是在路径?是在、如何获得、路径、大会

2023-09-02 01:16:35 作者:ぐ温柔行凶者

有没有办法来获取其中当前code所在的程序集的路径?我不想调用程序集的路径,只包含code中的之一。

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:项目 MyApplication的 daotests 斌调试 daotests.dll

C:projectsmyapplicationdaotestsbinDebugdaotests.dll

和我想获得这个路径:

C:项目 MyApplication的 daotests 斌调试

C:projectsmyapplicationdaotestsbinDebug

这三个建议,至今让我失望,当我从MbUnit的贵运行:

The three suggestions so far fail me when I run from the MbUnit Gui:

Environment.CurrentDirectory 给人的 C: Program Files文件 MbUnit的的

System.Reflection.Assembly.GetAssembly(typeof运算(DaoTests))。位置 给人的 C: Documents和 设置乔治本地 设置 TEMP .... DaoTests.dll 的

System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location gives C:Documents and SettingsgeorgeLocal SettingsTemp ....DaoTests.dll

System.Reflection.Assembly.GetExecutingAssembly()。位置 给出相同的previous

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);
    }
}

使用NUnit(其中组件从临时文件夹中运行)的时候,所以我preFER使用 codeBase的,让你的URI格式,则 UriBuild.UnescapeDataString 的路径删除文件:// 开头,而 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.