Skip to content

Instantly share code, notes, and snippets.

@svick
Created November 2, 2021 10:03
Show Gist options
  • Save svick/ffaa5d3fc3ef66479a6aa5811a3cd8e9 to your computer and use it in GitHub Desktop.
Save svick/ffaa5d3fc3ef66479a6aa5811a3cd8e9 to your computer and use it in GitHub Desktop.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build" Version="16.11.0" ExcludeAssets="runtime" />
<PackageReference Include="Microsoft.Build.Locator" Version="1.4.1" />
</ItemGroup>
</Project>
using System;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Locator;
// Note: code using MSBuild has to be in another method than the call to MSBuildLocator
MSBuildLocator.RegisterDefaults();
string GetAppHostPath()
{
var xml = @"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>";
var project = Project.FromXmlReader(XmlReader.Create(new StringReader(xml)), options: new()).CreateProjectInstance();
project.Build("ProcessFrameworkReferences", loggers: null);
return project.GetItems("AppHostPack").Single().GetMetadata("Path").EvaluatedValue;
}
Console.WriteLine(GetAppHostPath());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment