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

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


当前回答

string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);

其他回答

这有用吗?

//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 );
string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);

您所在的当前目录。

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;

我发现我的解足够检索位置。

var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;

据我所知,大多数其他答案都有一些问题。

对于基于磁盘的(而不是基于web的)非gaced程序集,正确的方法是使用当前正在执行的程序集的CodeBase属性。

返回一个URL (file://)。不需要处理字符串操作或UnescapeDataString,可以通过利用Uri的LocalPath属性进行转换。

var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
var directoryPath = Path.GetDirectoryName(filePathToCodeBase);