从代码构建visual studio解决方案

时间:2014-03-06 14:45:59

标签: c# visual-studio-2012 msbuild

我正在编写一个控制台应用程序来从tfs服务器获取解决方案,构建它并在iis上发布,但我仍然坚持构建......

我发现这个代码就像魅力一样

public static void BuildProject()
{
    string solutionPath = Path.Combine(@"C:\MySolution\Common\Common.csproj");

    List<ILogger> loggers = new List<ILogger>();
    loggers.Add(new ConsoleLogger());
    var projectCollection = new ProjectCollection();
    projectCollection.RegisterLoggers(loggers);
    var project = projectCollection.LoadProject(solutionPath);
    try
    {
        project.Build();
    }
    finally
    {
        projectCollection.UnregisterAllLoggers();
    }
}

但我的解决方案非常庞大并且包含多个相互依赖的项目(例如项目A引用了项目B)

如何获得构建每个项目的正确顺序? 有没有办法从.sln文件构建整个解决方案?

1 个答案:

答案 0 :(得分:9)

尝试使用以下代码加载解决方案并进行编译:

string projectFilePath = Path.Combine(@"c:\solutions\App\app.sln");

ProjectCollection pc = new ProjectCollection();

// THERE ARE A LOT OF PROPERTIES HERE, THESE MAP TO THE MSBUILD CLI PROPERTIES
Dictionary<string, string> globalProperty = new Dictionary<string, string>();
globalProperty.Add("OutputPath", @"c:\temp");

BuildParameters bp = new BuildParameters(pc);
BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0", new string[] { "Build" }, null);
// THIS IS WHERE THE MAGIC HAPPENS - IN PROCESS MSBUILD
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
// A SIMPLE WAY TO CHECK THE RESULT
if (buildResult.OverallResult == BuildResultCode.Success)
{              
    //...
}