使用 Microsoft.Build.Execution.BuildManager.DefaultBuildManager 编译时获取“未找到 Microsoft.CSharp.Core.targets”

问题描述 投票:0回答:1

我有一组在 Visual Studio 2022 上成功编译和构建的项目。

我想以编程方式构建它们。为此,我创建了一个构建器项目,它使用

Microsoft.Build.Execution.BuildManager.DefaultBuildManager
:

            var pc = new ProjectCollection();

            //There are a lot of properties here, these map to the msbuild CLI properties
            var globalProperty = new Dictionary<string, string>() {

                { nameof(DTOBuildGlobalProperty.OutDir), BuildGlobalProperty.OutDir },
                { nameof(DTOBuildGlobalProperty.Platform), BuildGlobalProperty.Platform },
                { nameof(DTOBuildGlobalProperty.Configuration), BuildGlobalProperty.Configuration },
                { nameof(DTOBuildGlobalProperty.TargetFramework),$"clean,{BuildGlobalProperty.TargetFramework}"}
            };

            BuildManager.DefaultBuildManager.ResetCaches();

            var bp = new BuildParameters(pc) {
                Loggers = new List<Microsoft.Build.Framework.ILogger>() {
                    new FileLogger() { Parameters = $@"logfile={BuildGlobalProperty.OutDir}\buildme.log;append" }
                }
            };

            var brequest = new BuildRequestData(path
                , globalProperty
                , null
                , new string[] {
                    BuildGlobalPropertyTargetToBuild.Restore.ToString(),
                    BuildGlobalProperty.TargetToBuild.ToString()
                }
                , null);

            var bresult = Microsoft.Build.Execution.BuildManager.DefaultBuildManager.Build(bp, brequest);

此代码会生成一个日志文件,其中包含以下消息:

error MSB4019: The imported project "bin\x86\Debug\Roslyn\Microsoft.CSharp.Core.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

当然,构建失败了。

值得注意的是,此代码曾经与作为 phisical .dll 添加的

Microsoft.Build
版本
15.1.0.0
一起使用;当我尝试升级我的构建器项目以使用 packageReferences 并添加来自 Nuget 的
Microsoft.Build
版本
17.8.3
时,我开始注意到这个问题。

如何更正上面的代码才能工作?

备注:

我已经检查过类似的问题和答案(例如\MSBuild .0\Bin\Microsoft.CSharp.targets file not found),但没有成功。

c# build roslyn
1个回答
0
投票

在调用 MSBuild 构建之前,需要使用 MSBuildLocator 指定正在使用的版本。这为 MSBuild 设置了各种环境位,指定加载某些任务和目标的位置。

© www.soinside.com 2019 - 2024. All rights reserved.