如何使用BuildManager在Visual Studio 2017上构建.Net Core项目或解决方案(MsBuild 15)

时间:2017-04-19 12:16:57

标签: c# msbuild .net-core visual-studio-2017

我想构建一个简单的项目或解决方案(VS 2017,.NET Standard / .Net Core)

ProjectCollection pc = new ProjectCollection();
pc.DefaultToolsVersion = "15.0";            
ILogger logger = new ConsoleLogger();
pc.Loggers.Add(logger);
Dictionary<string, string> globalProperty = new Dictionary<string, string>();
BuildRequestData buildRequest = new BuildRequestData(fileName, globalProperty, null, new[] { target }, null);
BuildParameters buildParameters = new BuildParameters(pc)
{
    DefaultToolsVersion = "15.0",
    OnlyLogCriticalEvents = false,
    DetailedSummary = true,
    Loggers = new List<Microsoft.Build.Framework.ILogger> { logger }.AsEnumerable()
};
var result = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
return result.OverallResult == BuildResultCode.Success;

但是构建失败并出现以下错误

MSBUILD : warning MSB4196: The "*.overridetasks" files could not be successfully loaded from their expected location "C:\Program Files\dotnet". Default tasks will not be overridden.
MSBUILD : warning MSB4010: The "*.tasks" files could not be successfully loaded from their expected location "C:\Program Files\dotnet". Default tasks will not be available.
D:\Build\workspace\Lx\Lx.sln.metaproj : error MSB4036: The "Message" task was not found. 
Check the following: 
1.) The name of the task in the project file is the same as the name of the task class. 
2.) The task class is "public" and implements the Microsoft.Build.Framework.ITask interface. 
3.) The task is correctly declared with <UsingTask> in the project file, or in the *.tasks files located in the "C:\Program Files\dotnet" directory.

似乎无法找到正确的目录或者这样的...... 我该怎么做才能解决这个问题?

注意:我不想从其他目录中复制文件。

1 个答案:

答案 0 :(得分:1)

为了将BuildManager与.Net Core / Visual Studio 2017 / MsBuild 15一起使用,您必须设置几个环境变量:

var msbuildRoot = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild";
var msbuildExe = Path.Combine(msbuildRoot, @"15.0\Bin\MsBuild.exe");
var sdkPath = Path.Combine(msbuildRoot, "Sdks"); 
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", msbuildExe);
Environment.SetEnvironmentVariable("MSBUILDSDKSPATH", sdkPath);
Environment.SetEnvironmentVariable("MSBuildExtensionsPath", msbuildRoot);

请注意,在对MsBuild类进行任何访问之前,应先设置前两个。这是因为BuildEnvironmentHelper在静态初始化(Singleton模式)中读取它们。检查方法TryFromEnvironmentVariable以获取更多详细信息。

然而,最后一个MSBuildExtensionsPath可以由全局属性设置:

globalProperties.Add("MSBuildExtensionsPath", msbuildRoot);