I had similar needs for my team and I wrote a Builder library for C# that supports several versions of Visual Studio.
I could not make the Project.Build function work properly, so I went for executing MsBuild.exe directly.
How I built it:
Use Microsoft.Build.Framework from NuGet
Create a new Project object with 1 target called Build
Define the right ToolsVersion
Of the Project according to the Visual Studio version:
- 2010, 2012 => 4.0
- 2013 => 12.0
- 2015 => 14.0
- 2017 => 15.0
Add a new task of type MsBuild
With Projects property containing all the project I need to build
Define the ToolsVersion
of the MsBuild task with same value as for the Project
Serialize the Project into a temporary file
Find the right MsBuild.exe according to the ToolsVersion
4.0, 12.0, 14.0
Found in the registry:
Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{msBuildVersion}")
15.0
Not anymore in the registry, you need to use the Nuget package Microsoft.VisualStudio.Setup.Configuration.Interop
var query = new SetupConfiguration();
var query2 = (ISetupConfiguration2)query;
var e = query2.EnumAllInstances();
var helper = (ISetupHelper)query;
int fetched;
var instances = new ISetupInstance[1];
do
{
e.Next(1, instances, out fetched);
if (fetched > 0)
{
var instance = instances[0];
var instance2 = (ISetupInstance2)instance;
var state = instance2.GetState();
// Skip non-complete instance, I guess?
// Skip non-local instance, I guess?
// Skip unregistered products?
if (state != InstanceState.Complete
|| (state & InstanceState.Local) != InstanceState.Local
|| (state & InstanceState.Registered) != InstanceState.Registered)
{
continue;
}
var msBuildComponent =
instance2.GetPackages()
.FirstOrDefault(
p =>
p.GetId()
.Equals("Microsoft.Component.MSBuild",
StringComparison.InvariantCultureIgnoreCase));
if (msBuildComponent == null)
{
continue;
}
var instanceRootDirectory = instance2.GetInstallationPath();
var msbuildPathInInstance = Path.Combine(instanceRootDirectory, "MSBuild", msBuildVersion, "Bin", "msbuild.exe");
if (File.Exists(msbuildPathInInstance))
{
return msbuildPathInInstance;
}
}
} while (fetched > 0);
Execute MsBuild.exe
And build the serialized Project using a custom XML Logger - you can use the one provided by MsBuildExtensionPack
Read the result summary
Deserialize the result summary from Xml and use it to determine if build failed or not, which errors and warnings occurred etc.
AppDomain.CurrentDomain.AssemblyResolve
to point resolution to the MSBuild folder itself. In either case there's no toolset version 15 available.