How to get the value of an MSBuild variable

2019-09-09 19:38发布

问题:

How can I get the value of MSBuild variable (ex. $(MSBuildToolsPath), $(MSBuildAssemblyVersion), $(TargetFrameworkIdentifier), etc.).

I need to get the value on the C# side, but I can access msbuild.exe if it's not available from the C# code.

回答1:

BuildManager and the likes are for building, only; Microsoft decided to split up the MSBuild API in different namespaces according to functionality. Once you know that it's not too hard figuring out what you need: you just need to evaluate properties, so the Project class from the Evaluation namespace seems like the proper choice. It has a Properties member exposing all properties:

var project = new Microsoft.Build.Evaluation.Project( @"my.vcxproj" );
foreach( var property in p.Properties )
{
  System.Console.WriteLine( "{0} = {1}",
    property.Name, property.EvaluatedValue );
}


标签: msbuild