首页 > 解决方案 > 如何从不同项目文件夹的输出目录访问运行时中的文件

问题描述

我们在 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(),但有什么替代方法。不知何故,我可以使用上述替换程序集名称的肮脏方式访问它。

标签: c#visual-studio

解决方案


首先,我建议您可以在解决方案中找到 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
                    }
                }
            }

        }

推荐阅读