解決一個問題後,最好的慶祝方式就是寫一篇部落格。今天解決了一個小問題,小小慶祝一下。
這個小問題是什嗎?
答:如何在ASP.NET調用MsBuild編譯一個VS2010解決方案?
是什麼需求帶來的這個問題?
答:發布一個網站的新版本時,通過瀏覽器觸發Web伺服器從Git版本控制伺服器中取出最新代碼,然後調用MsBuild進行編譯。。。
如何解決這個小問題的:
答:在ASP.NET中通過System.Diagnostics.Process運行msbuild.exe。
代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
protected override void OnInit(EventArgs e)
{
string filePath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe";
//以release方式編譯CNBlogsJob.sln
ProcessStartInfo info = new ProcessStartInfo(filePath, @" E:\Dev\CNBlogsJob.sln /p:Configuration=release");
//將控制台輸出重新導向至StandardOutput,如果為false,就無法得到控制台輸出結果
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
//下面一行代碼是為了類比控制台的顯示效果
Response.Write("<body style=\"color:#DDD;background-color:#000;\">");
//控制台輸出結果
Response.Write(p.StandardOutput.ReadToEnd().Replace("\n","<br/>"));
Response.Write("</body>");
p.WaitForExit();
p.Close();
}
</script>
瀏覽器中顯示的結果: