.jpg)
有没有办法获取当前代码所在的程序集的路径?我不想要调用程序集的路径,只需要包含代码的路径。
基本上我的单元测试需要读取一些相对于dll的xml测试文件。我希望路径始终正确解析,无论测试 dll 是从 TestDriven.NET、MbUnit GUI 还是其他东西运行的。
编辑:人们似乎误解了我在问什么。
我的测试库位于 说
C:projectsmyapplicationdaotestsbinDebugdaotests.dll
我想得到这条路:
C:projectsmyapplicationdaotestsbinDebug
到目前为止,当我从 MbUnit Gui 运行时,这三个建议让我失望了:
Environment.CurrentDirectorySystem.Reflection.Assembly.GetAssembly(typeof(DaoTests)).LocationSystem.Reflection.Assembly.GetExecutingAssembly().Location
网友回答:
这有帮助吗?
//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 );

网友回答:
注意: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);
}
}
使用 NUnit(程序集从临时文件夹运行)时,该属性有时会为您提供一些有趣的结果,因此我更喜欢使用它为您提供 URI 格式的路径,然后删除开头的路径,并将其更改为普通的窗口格式。Assembly.LocationCodeBaseUriBuild.UnescapeDataStringFile://GetDirectoryName

网友回答:
就这么简单:
var dir = AppDomain.CurrentDomain.BaseDirectory;
模板简介:该模板名称为【 如何获取代码所在的程序集的路径?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。