【C#】プログラムからプロジェクトファイルを指定してMSBuildを実行

using System.Diagnostics;
using System.Text;
using System.Xml;

/// <summary>
/// MSBuildのパス。
/// </summary>
private const string MSBuildPath = @"C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe";

/// <summary>
/// MSBuildを実行する。
/// </summary>
/// <param name="projectFilePath">プロジェクトファイルのパス。</param>
/// <param name="outputDirPath">出力フォルダのパス。</param>
/// <param name="isDebug">デバッグビルドかどうか。</param>
/// <param name="outputDataReceivedEventHandler">MSBuildの出力読み取りハンドラ。</param>
/// <param name="errorDataReceivedEventHandler">MSBuildのエラー出力読み取りハンドラ。</param>
/// <returns>MSBuildの戻り値。</returns>
private int ExecuteMSBuild(string projectFilePath,
                           string outputDirPath,
                           bool isDebug,
                           DataReceivedEventHandler outputDataReceivedEventHandler,
                           DataReceivedEventHandler errorDataReceivedEventHandler)
{
    using (Process p = new Process())
    {
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        p.StartInfo.UseShellExecute = true;
        p.StartInfo.FileName = MSBuildPath;
        // パラメータについては「http://msdn.microsoft.com/ja-jp/library/bb629394.aspx」参照
        StringBuilder args = new StringBuilder();
        args.AppendFormat("\"{0}\"", projectFilePath);                              // プロジェクトファイル
        args.AppendFormat(" /p:Configuration={0}", isDebug ? "Debug" : "Release");  // ビルド構成
        args.AppendFormat(" /p:OutputPath=\"{0}\"", outputDirPath);                 // 出力フォルダ
        args.Append(" /p:OptionExplicit=true");                                     // 変数の宣言を強制
        args.Append(" /p:OptionCompare=binary");                                    // バイナリで文字列比較
        args.Append(" /p:OptionStrict=true");                                       // 暗黙的な型変換を無効
        args.Append(" /p:OptionInfer=true");                                        // 変数の型の推論を可能
        args.Append(" /p:BuildProjectReferences=false");                            // プロジェクト参照をビルドするか
        args.AppendFormat(" /p:DebugType={0}", isDebug ? "full" : "none");          // デバッグ情報の出力
        args.AppendFormat(" /p:DebugSymbols={0}", isDebug ? "true" : "false");      // pdbファイルを生成するか
        args.AppendFormat(" /p:DocumentationFile={0}", isDebug ? string.Format("{0}.xml", GetAssemblyName(projectFilePath)) : " "); // XMLドキュメントファイル
        args.Append(" /t:Clean;Rebuild");
        p.StartInfo.Arguments = args.ToString();

        // 出力をハンドリングする場合
        if (outputDataReceivedEventHandler != null || errorDataReceivedEventHandler != null)
        {
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            if (outputDataReceivedEventHandler != null)
            {
                p.StartInfo.RedirectStandardOutput = true;
                p.OutputDataReceived += outputDataReceivedEventHandler;
            }

            if (errorDataReceivedEventHandler != null)
            {
                p.StartInfo.RedirectStandardError = true;
                p.ErrorDataReceived += errorDataReceivedEventHandler;
            }
        }

        // MSBuild実行
        p.Start();

        // 出力の非同期読み取り
        if (outputDataReceivedEventHandler != null)
            p.BeginOutputReadLine();

        // エラー出力の非同期読み取り
        if (errorDataReceivedEventHandler != null)
            p.BeginErrorReadLine();

        // MSBuild実行完了まで待機
        p.WaitForExit();

        // MSBuildの戻り値を返す
        return p.ExitCode;
    }
}

/// <summary>
/// プロジェクトファイルからアセンブリ名を取得する。
/// </summary>
/// <param name="projectFilePath">プロジェクトファイルのパス。</param>
/// <returns>アセンブリ名。</returns>
private static string GetAssemblyName(string projectFilePath)
{
    // プロジェクトファイルをXMLとしてロード
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(projectFilePath);

    // 名前空間を定義
    XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
    xnm.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");

    // アセンブリ名ノードを取得
    XmlNode node = xdoc.SelectSingleNode("/ns:Project/ns:PropertyGroup/ns:AssemblyName", xnm);

    // アセンブリ名を返す
    if (node != null)
        return node.InnerText;
    else
        return "";
}