如何通过Microsoft.Build获取Visual Studio解决方案的Solution Items文件?
获取Visual Studio解决方案中Solution Items的文件列表
方法一:借助Microsoft.Build官方API提取
SolutionFile.Parse返回的对象中,Solution Folder对应的SolutionProject实例包含ProjectSections集合,其中SolutionItems类型的Section存储了所有关联文件。具体实现:
- 解析解决方案:
var solutionFile = SolutionFile.Parse(@"path\to\your\solution.sln");
- 筛选目标Solution Folder:
Solution Folder的类型GUID固定为{2150E333-8FDC-42A3-9474-1A3956D46DE8},以此定位名为“Solution Items”的文件夹:
var solutionItemsFolder = solutionFile.Projects .FirstOrDefault(p => p.TypeGuid.ToString().Equals("{2150E333-8FDC-42A3-9474-1A3956D46DE8}", StringComparison.OrdinalIgnoreCase) && p.Name == "Solution Items");
- 提取文件路径:
找到对应Section后,遍历其Entries即可获取文件相对路径:
if (solutionItemsFolder != null) { var solutionItemsSection = solutionItemsFolder.ProjectSections .FirstOrDefault(s => s.SectionType == "SolutionItems"); if (solutionItemsSection != null) { foreach (var entry in solutionItemsSection.Entries) { // entry.Key为文件相对路径,entry.Value是sln内的标识GUID Console.WriteLine($"Solution Item: {entry.Key}"); } } }
方法二:直接解析.sln文件文本
若官方API因版本限制无法使用,可直接读取并解析sln文件内容:
- 读取sln文件:
var slnLines = File.ReadAllLines(@"path\to\your\solution.sln");
- 定位并提取文件:
遍历行内容,匹配Solution Items项目块及内部的SolutionItems Section:
bool inSolutionItemsProject = false; bool inSolutionItemsSection = false; foreach (var line in slnLines) { var trimmedLine = line.Trim(); if (trimmedLine.StartsWith(@"Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""Solution Items""")) { inSolutionItemsProject = true; continue; } if (inSolutionItemsProject && trimmedLine == "EndProject") { inSolutionItemsProject = false; inSolutionItemsSection = false; continue; } if (inSolutionItemsProject && trimmedLine.StartsWith("ProjectSection(SolutionItems) = preProject")) { inSolutionItemsSection = true; continue; } if (inSolutionItemsSection && trimmedLine == "EndProjectSection") { inSolutionItemsSection = false; continue; } if (inSolutionItemsSection && !string.IsNullOrWhiteSpace(trimmedLine)) { var parts = trimmedLine.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { Console.WriteLine($"Solution Item: {parts[0]}"); } } }
注意点
- 确认使用的Microsoft.Build 17.10.4版本中,
SolutionProject.ProjectSections属性已公开(部分早期版本可能未开放)。 - 获取到的是相对解决方案的路径,可通过
Path.Combine(Path.GetDirectoryName(slnPath), relativePath)转换为绝对路径。
内容的提问来源于stack exchange,提问作者C Robinson
相关产品推荐
相关产品推荐

