有没有办法获取当前代码所在程序集的路径?我不想要调用程序集的路径,只想要包含代码的路径。
基本上我的单元测试需要读取一些相对于 dll 定位的 xml 测试文件。无论测试 dll 是从 TestDriven.NET、MbUnit GUI 还是其他东西运行,我都希望路径始终正确解析。
编辑:人们似乎误解了我的问题。
我的测试库位于say
C:\projects\myapplication\daotests\bin\Debug\daotests.dll
我想得到这条路:
C:\projects\myapplication\daotests\bin\Debug\
当我从 MbUnit Gui 运行时,到目前为止的三个建议都让我失望:
Environment.CurrentDirectory
给出 c:\Program Files\MbUnitSystem.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location
给出 C:\Documents 和 设置\乔治\本地 Settings\Temp\....\DaoTests.dllSystem.Reflection.Assembly.GetExecutingAssembly().Location
给出与之前相同的结果。
最佳答案
注意:Assembly.CodeBase 在 .NET Core/.NET 5+ 中已弃用:https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0
原答案:
我定义了以下属性,因为我们经常在单元测试中使用它。
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);
}
}
Assembly.Location
属性在使用 NUnit 时有时会给你一些有趣的结果(程序集从临时文件夹运行),所以我更喜欢使用 CodeBase
它给你URI格式的路径,然后UriBuild.UnescapeDataString
去掉开头的File://
,GetDirectoryName
改成正常的windows格式.
关于c# - 如何获取代码所在程序集的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797/