Skip to content

Instantly share code, notes, and snippets.

@TimothyDJewell
Last active August 10, 2023 14:19
Show Gist options
  • Save TimothyDJewell/ef0b35709afc4c52c6482b894f6b7169 to your computer and use it in GitHub Desktop.
Save TimothyDJewell/ef0b35709afc4c52c6482b894f6b7169 to your computer and use it in GitHub Desktop.
Load basic information about a .NET solution file
<Query Kind="Program">
<NuGetReference>Microsoft.Build</NuGetReference>
<NuGetReference>Microsoft.Build.Utilities.Core</NuGetReference>
</Query>
void Main()
{
ExtractProjectData(@"Path\To\Solution\File.sln").Dump();
}
public IEnumerable<ProjectData> ExtractProjectData(string pathToSolution)
{
var solution = Microsoft.Build.Construction.SolutionFile.Parse(pathToSolution);
var allProjects = solution.ProjectsInOrder.Where(p => p.ProjectType != Microsoft.Build.Construction.SolutionProjectType.SolutionFolder)
.Select(p => new { p.ProjectName, p.AbsolutePath, ProjectFileInfo = new FileInfo(p.AbsolutePath) })
.ToList();
return allProjects.Select(p => new { ProjectData = p, Instance = new Microsoft.Build.Execution.ProjectInstance(p.AbsolutePath) })
.Select(p => new ProjectData
{
ProjectName = p.ProjectData.ProjectName,
TargetFrameworkVersion = p.Instance.Properties.SingleOrDefault(pr => pr.Name == "TargetFrameworkVersion")?.EvaluatedValue,
TargetFrameworkMoniker = p.Instance.Properties.SingleOrDefault(pr => pr.Name == "TargetFrameworkMoniker")?.EvaluatedValue,
TargetExt = p.Instance.Properties.SingleOrDefault(pr => pr.Name == "TargetExt")?.EvaluatedValue,
OutputType = p.Instance.Properties.SingleOrDefault(pr => pr.Name == "OutputType")?.EvaluatedValue,
ProjectReferences = p.Instance.Items.Where(i => i.ItemType == "ProjectReference")
.Select(reference =>
{
string referencePath = new FileInfo(Path.Combine(p.ProjectData.ProjectFileInfo.DirectoryName, reference.EvaluatedInclude)).FullName;
return allProjects.FirstOrDefault(f => f.ProjectFileInfo.FullName == referencePath)?.ProjectName;
}).ToList(),
});
}
public class ProjectData
{
public string ProjectName { get; set; }
public string TargetFrameworkVersion { get; set; }
public string TargetFrameworkMoniker { get; set; }
public string TargetExt { get; set; }
public string OutputType { get; set; }
public IReadOnlyCollection<string> ProjectReferences { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment