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

基本上,我的单元测试需要读取一些相对于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 () 给出与前面相同的结果。


当前回答

这应该可以工作:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);

string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");

我使用它来部署DLL文件库以及一些配置文件(这是从DLL文件中使用log4net)。

其他回答

这样如何……

string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

然后砍掉你不需要的部分

这应该可以工作,除非程序集是影子复制的:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location

这是一个VB。John bly代码的NET移植。Visual Basic不区分大小写,所以他的几个变量名会与类型名发生冲突。

Public Shared ReadOnly Property AssemblyDirectory() As String
    Get
        Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase
        Dim uriBuilder As New UriBuilder(codeBase)
        Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)
        Return Path.GetDirectoryName(assemblyPath)
    End Get
End Property

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

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

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

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

您所在的当前目录。

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

如果您使用build复制.xml文件,您应该可以找到它。

or

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

// The location of the Assembly
assembly.Location;