如何在不使用命令提示符的情况下使用 MSBuild 引擎构建多个 c# 项目?

How to build multiple c# projects using MSBuild engine without using command prompt?

我正在开发 windows 应用程序项目,并且希望从该项目构建不同的多个 c# 项目,这些项目位于 visual studio 2015 的一个解决方案中,并且还希望它们被构建 programmatically 在不使用命令提示符的情况下单独使用 MSBuild 工具,最后想在日志文件中而不是在命令提示符中显示输出(意味着这些项目正在成功构建或在日志文件中出现类似此消息的任何错误)

我需要使用任何 MSBuild API 以及如何添加到这个项目中吗?

我见过很多这样的问题(不完全相同),但它对我不起作用。请问有人可以帮我吗?

    using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Logging;

...
 public static BuildResult Compile(string solution_name, out string buildLog)
        {
                buildLog = "";
                string projectFilePath = solution_name;
                ProjectCollection pc = new ProjectCollection();
                Dictionary<string, string> globalProperty = new Dictionary<string, string>();
                globalProperty.Add("nodeReuse", "false");
                BuildParameters bp = new BuildParameters(pc);
                bp.Loggers = new List<Microsoft.Build.Framework.ILogger>()
                {
                    new FileLogger() {Parameters = @"logfile=buildresult.txt"}
                };
                BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0",
                    new string[] {"Clean", "Build"}, null);
                BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
                BuildManager.DefaultBuildManager.Dispose();

                pc = null;
                bp = null;
                buildRequest = null;

                if (buildResult.OverallResult == BuildResultCode.Success)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                else
                {
                    if (Directory.Exists("C:\BuildResults") == false)
                    {
                        Directory.CreateDirectory("C:\BuildResults");
                    }
                    buildLog = File.ReadAllText("buildresult.txt");
                    Console.WriteLine(buildLog);
                    string fileName = "C:\BuildResults\" + DateTime.Now.Ticks + ".txt";
                    File.Move("buildresult.txt", fileName);
                    Console.ForegroundColor = ConsoleColor.Red;

                    Thread.Sleep(5000);
                }
                Console.WriteLine("Build Result " + buildResult.OverallResult.ToString());
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("================================");




                return buildResult;

        }

这是我手头的一些旧代码。 我使用它以编程方式构建解决方案和 C# 项目。输出将是 BuildResult.Success 或 BuildResult.Failure。 变量 buildLog 将包含构建输出。 注意 - 据我所知,访问构建输出的唯一方法是使用上述生成日志文件的方法,然后在 C# 代码中读取它。

需要注意的一件事是,我从未找到解决此问题的方法是,运行使用此代码的应用程序可能会将其 dll 从内存中的 nuget 包目录加载到内存中。这使得删除这些目录有问题。我通过将我的应用程序 运行 作为 MS 服务找到了解决方法 - 似乎当它 运行 作为本地服务时,它有足够的权限删除内存中保存的文件。