使用Microsoft.Build API构建项目

我正在尝试使用Microsoft.Build中的类来构建项目。

代码是:

var project = new ProjectInstance(CS_PROJ_FILE); project.Build(); 

然而,它抛出以下exception:

 Microsoft.Build.Shared.InternalErrorException occurred HResult=0x80131500 Message=MSB0001: Internal MSBuild Error: Type information for Microsoft.Build.Utilities.ToolLocationHelper was present in the whitelist cache as Microsoft.Build.Utilities.ToolLocationHelper, Microsoft.Build.Utilities.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a but the type could not be loaded. unexpectedly null Source=Microsoft.Build 

我已经尝试将以下内容添加到包中(在net452和net7项目中):

  • id =“Microsoft.Build”version =“15.1.1012”
  • id =“Microsoft.Build.Framework”version =“15.1.1012”
  • id =“Microsoft.Build.Runtime”version =“15.1.1012”
  • id =“Microsoft.Build.Tasks.Core”version =“15.1.1012”
  • id =“Microsoft.Build.Utilities.Core”version =“15.1.1012”

仍然得到相同的结果。

我也试过像这样使用BuildManager

 var buildManager = new BuildManager(); buildManager.Build(new BuildParameters(), new BuildRequestData(new ProjectInstance(CS_PROJ_FILE), new[] {"Build"})); 

我安装后遇到了同样的错误:

 Install-Package Microsoft.Build -Version 15.1.1012 

但后来我安装了:

 Install-Package Microsoft.Build.Utilities.Core -Version 15.1.1012 

事情开始奏效了。

有点混乱……

我被“dasMulli”指向了这个stackoverflow问题:

https://github.com/Microsoft/msbuild/issues/1889

显然有一种解决这个问题的新方法,如此处和此处所述 。

这对我有用:

  1. 我从项目的输出中删除了Microsoft.Build.dllMicrosoft.Build.Framework.dllMicrosoft.Build.Tasks.Core.dllMicrosoft.Build.Utilities.Core.dll (即所有Microsoft.Build .dll文件)夹。

  2. 我从项目的引用中删除了几个Microsoft.Build NuGet包。

  3. 我为我的项目安装了Microsoft.Build.Locator NuGet包。

  4. 我在程序中添加了以下代码:

      // This needed after upgrading to Roslyn revision 34025, see these two links: // https://github.com/dotnet/roslyn/issues/26029 // https://stackoverflow.com/a/49886334/253938 MSBuildLocator.RegisterDefaults(); 

这修复了OP列出的exception避免了大量无法解析所有引用的编译器错误消息。

编辑:更多信息: https : //gist.github.com/DustinCampbell/32cd69d04ea1c08​​a16ae5c4cd21dd3a3