【发布时间】:2015-08-12 13:59:41
【问题描述】:
在查看了整个 Google 之后,我找到了构建解决方案的好方法。但是,我要构建的解决方案还包含单元测试项目,我不想将其包含在构建中,或者如果我无法阻止,至少将这些二进制文件放在单独的文件夹中。代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
public class BuildSolution
{
private readonly string _solutionPath;
private readonly string _outputPath = "C:\\Temp\\TestBuild\\";
public BuildSolution(string solutionPath, string outputPath = null)
{
if (!string.IsNullOrEmpty(outputPath))
_outputPath = outputPath;
_solutionPath = solutionPath;
Directory.EnumerateFiles(_outputPath, "*", SearchOption.AllDirectories)
.Select(x => new FileInfo(x))
.ToList()
.ForEach(x => x.Delete());
}
public void Build()
{
var pc = new ProjectCollection();
var globalProps = new Dictionary<string, string>()
{
{ ProjectPropertyNames.Configuration, "Debug" },
{ ProjectPropertyNames.OutputPath, _outputPath },
{ ProjectPropertyNames.EnableNuGetPackageRestore, "true"},
};
var targetsToBuild = new[] { "Build" };
var buildRequest = new BuildRequestData(_solutionPath, globalProps, null, targetsToBuild, null);
var buildParams = new BuildParameters(pc);
buildParams.Loggers = new List<ILogger>() { new ConsoleLogger(LoggerVerbosity.Minimal) };
var buildManager = BuildManager.DefaultBuildManager;
buildManager.BeginBuild(buildParams);
var buildSubmission = buildManager.PendBuildRequest(buildRequest);
buildSubmission.ExecuteAsync(BuildCompleted, null);
while (!done)
{
Thread.Sleep(10);
}
buildManager.EndBuild();
Console.WriteLine("OverallResult:{0}", buildSubmission.BuildResult.OverallResult);
}
bool done = false;
private void BuildCompleted(BuildSubmission submission)
{
done = submission.IsCompleted;
}
/// <summary>
/// Unused, but I tried it and it gives me back the correct projects but the build fails because of dependant nuget packages
/// </summary>
/// <param name="path">path of solution</param>
/// <returns></returns>
private IEnumerable<FileInfo> GetFirstLevelProjects(string path)
{
foreach (var dir in Directory.EnumerateDirectories(path))
{
foreach (var file in Directory.EnumerateFiles(dir, "*.csproj"))
{
if (!file.Contains("Test"))
yield return new FileInfo(file);
}
}
}
}
没什么好看的。 (我正在考虑使构建异步的想法,以便我可以更新状态......我们会看到的,我可能会将其切换回同步)。我尝试过的一件事是,我不会将解决方案放在构建请求中,而是使用第一级项目构建项目集合(我将 git 与子模块一起使用,所以我不想构建所有不相关的子-模块)。该路线的问题在于构建会因为 nuget 包而失败(不知道为什么或如何解决这个问题)。当我构建解决方案时,它会成功构建,但我的 outputPath 还包含测试二进制文件。我的最终游戏是输出可以复制到我的特定文件夹中。如果我知道我可以过滤测试项目中的所有二进制文件,我不介意拥有测试二进制文件......那怎么办?我有什么选择?
【问题讨论】: