在调试编码的 ui 中运行代码时,如何获取文件的相对路径
本文关键字:何获取 获取 文件 路径 相对 ui 编码 调试 运行 代码 | 更新日期: 2023-09-27 18:33:20
我试图不对我的路径进行硬编码,但我无法找到一种方法来访问我包含在项目中标记为数据源的文件夹下的 xml 文件。这是我尝试过的最新代码,但仍然不起作用。
public static string myAssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
string fileName = xmlFileName;
string path = Path.Combine(myAssemblyDirectory, @"DataSource'" + fileName);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
这是我获得的路径的输出,该路径将其放在我的测试结果输出文件夹中。
"C:''MyAutomation''Automated_Test_Projects''AutomationProjects''MiserReleaseTestSuites''TestResults''marcw_ISD2005M 2016-02-05 10_15_17''Out''DataSource''Miser_Login_Dts.xml"
如果可能的话,我想指出它"C:''MyAutomation''Automated_Test_Projects''AutomationProjects''MiserReleaseTestSuites''MiserReleaseTestSuites''DataSource''Miser_Login_DTs.xml"
".."
可用于转到相对父目录。 "."
引用当前目录。
您可以将它们组合在一起,形成一个相对路径,该路径在目录树中从更高的位置开始。
在您的示例中,您需要转到比out
文件夹高 3 个目录,然后进入 MiserReleaseTestSuites'DataSource
文件夹。结合这个产生
@"..'..'..'MiserReleaseTestSuites'DataSource'"
您可以采用与数据驱动测试时相同的方式部署文件。见 https://stackoverflow.com/a/25742114/546871
TestContext
类包含多个名称中带有"目录"的字段。这些可用于访问与运行测试关联的各种目录。另请参阅 https://stackoverflow.com/a/19682311/546871