是否有方法获取当前代码所在程序集的路径?我不需要调用程序集的路径,只需要包含代码的路径。

基本上,我的单元测试需要读取一些相对于dll的xml测试文件。无论测试dll是否从TestDriven运行,我都希望该路径始终能够正确解析。NET, MbUnit GUI或者别的什么。

编辑:人们似乎误解了我的问题。

我的测试库位于say

C: \ \项目myapplication \ daotests \ bin \ \ daotests.dll调试

我想得到这条路径:

C: \ \ myapplication \ daotests \ bin \项目调试\

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

环境。CurrentDirectory 给出c:\Program Files\MbUnit System.Reflection.Assembly.GetAssembly .Location (typeof (DaoTests)) 给出C:\Documents和 乔治\ \本地设置 设置\ Temp \…\ DaoTests.dll .Location System.Reflection.Assembly.GetExecutingAssembly () 给出与前面相同的结果。


当前回答

AppDomain.CurrentDomain.BaseDirectory

工作与MbUnit GUI。

其他回答

从。net framework 4.6 / .net core 1.0开始,现在有了一个AppContext。BaseDirectory,它应该给出与AppDomain.CurrentDomain相同的结果。除了AppDomains不是.net core 1的一部分。X /.net标准x的API。

AppContext.BaseDirectory

编辑:文档现在甚至声明:

在. net 5.0及更高版本中,对于捆绑的程序集,返回的值是主机可执行文件的包含目录。

事实上,组装。定位医生医生说:

在. net 5.0及更高版本中,对于捆绑的程序集,返回的值是空字符串。

在windows窗体应用程序中,你可以简单地使用应用程序。StartupPath

但对于dll和控制台应用程序,代码更难记住…

string slash = Path.DirectorySeparatorChar.ToString();
string root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

root += slash;
string settingsIni = root + "settings.ini"

当我使用CodeBase和UNC网络共享时,唯一有效的解决方案是:

System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);

它也适用于普通uri。

如果路径包含“#”符号,则会得到不正确的目录。 所以我使用了John bly答案的一个修改,那就是组合UriBuilder。Path和UriBuilder。片段:

public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        //modification of the John Sibly answer    
        string path = Uri.UnescapeDataString(uri.Path.Replace("/", "\\") + 
          uri.Fragment.Replace("/", "\\"));
        return Path.GetDirectoryName(path);
     }
}

当开发人员可以更改代码以包含所需的代码片段时,所有建议的答案都是有效的,但如果您希望在不更改任何代码的情况下做到这一点,则可以使用Process Explorer。

它将列出系统中所有正在执行的dll,您可能需要确定正在运行的应用程序的进程id,但这通常并不太难。

我已经写了一个完整的描述如何在II - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/中为一个dll做到这一点