[英]How to access a file in runtime from output directory from a different project folder
我們在 Visual Studio 的一個解決方案下有一組測試項目。 我想讀取一個 Json 文件,該文件在運行時從不同的項目文件夾復制到 output 目錄。 這是一個測試項目。 我可以得到當前的項目目錄。 但不確定如何獲取其他程序集的目錄。
解決方案如下所示Project1 -> Sample.json(此文件設置為復制到 output 目錄) Project2
在 Project2 中運行我的測試時,我想從 output 目錄訪問 Project1 中的文件。
我曾經使用上述代碼訪問同一項目文件夾中的文件。 但不確定如何獲取不同的項目文件。 現在用替換我能夠實現它。 但確定這不是正確的方法
var filePath = Path.Combine("Sample.json");
var fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), filePath).Replace("Project1", "Project2");
不確定如何從其他項目中獲取。 我確定我不能使用GetExecutingAssembly() ,但有什么選擇。 不知何故,我可以使用上面替換程序集名稱的骯臟方式來訪問它。
要獲取另一個程序集的位置,您可以使用該程序集的類型來獲取正確的Assembly
實例,從而獲得它的位置:
typeof(FromOtherAssembly).Assembly.Location
首先,我建議您可以在解決方案中找到 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
}
}
}
}
您可以使用以下代碼以更好的方式執行此操作
//solutionpath will take you to the root directory which has the .sln file
string solutionpath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName);
string secondprojectname = @"SecondProjectName\bin";
string finalPath = Path.Combine(solutionpath, secondprojectname);
你可以在 MSBuild 中使用 CopyToOutputDirectory
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.