c# - 如何从不同项目文件夹的输出目录访问运行时中的文件
问题描述
我们在 Visual Studio 的一个解决方案下有一组测试项目。我想读取一个 Json 文件,该文件在运行时从不同的项目文件夹复制到输出目录。这是一个测试项目。我可以得到当前的项目目录。但不确定如何获取其他程序集的目录。
解决方案如下 Project1 -> Sample.json(此文件设置为复制到输出目录) Project2
在 Project2 中运行测试时,我想从输出目录访问 Project1 中的文件。
我曾经使用上述代码访问同一项目文件夹中的文件。但不确定如何获取不同的项目文件。现在通过替换我能够实现它。但肯定这不是正确的方法
var filePath = Path.Combine("Sample.json");
var fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), filePath).Replace("Project1", "Project2");
不知道如何从其他项目中获得。我确定我不能使用GetExecutingAssembly(),但有什么替代方法。不知何故,我可以使用上述替换程序集名称的肮脏方式访问它。
解决方案
首先,我建议您可以在解决方案中找到 dll 路径。
其次,您可以从路径中过滤json文件。
接下来是我的工作代码。
请先安装 Microsoft.Build 和 Microsoft.Build.Framework nugetpackages。
string path= string.Empty;
var solutionFile =SolutionFile.Parse(@"D:\test.sln");// Your solution place.
var projectsInSolution = solutionFile.ProjectsInOrder;
foreach (var project in projectsInSolution)
{
if(project.ProjectName=="TestDLL") //your dll name
{
path = project.AbsolutePath;
DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", path));
path = di.FullName;
foreach (var item in Directory.GetFiles(path,"*.json")) // filter the josn file in the correct path
{
if(item.StartsWith("Sample"))
{
Console.WriteLine(item);// you will get the correct json file path
}
}
}
}
推荐阅读
- razzle - 如何从 Razzle 中的 Web 模块中排除服务器模块
- assembly - 字节序会影响寄存器中的字节顺序还是仅影响 RAM 中的字节顺序?
- laravel - 为什么我想过滤项目时会出现这个问题
- php - 在浏览器上单击退格导航时如何防止访问管理端口
- android - 为什么 Android Studio 不能识别函数?
- javascript - 如何从我的网站自动登录到不同的网站,然后从他们的 HTML 中获取 href 链接?
- javascript - 在javascript中从数组中查找并删除嵌套元素?
- r - R:read_csv 将数字条目读取为逻辑 - 解析 col_logical 而不是 col_double
- php - Lumen 使用 Graph API 和社交名流
- c++ - 从主函数调用变量到其他类&无法使用它?