重定向但也显示进程输出流

我正在运行构建,我希望能够查看进展情况。 但是如果构建有错误,我还想保存输出。

我知道我可以使用Process.UseShellExecute = falseRedirectStandardOutput ,但这只是故事的一部分。

我怎样才能做到这一点?

更新

正如Greg在下面的评论中提到的那样,MSBuild可以写出日志文件,同时也可以开箱即用输出到控制台。

 MSBuild [options] /filelogger /fileloggerparameters:LogFile=MSBuildLog.txt 

尝试以下简单的C#程序。 它将重定向STDIN( Console.In )并将其写入一个或多个文件和STDOUT( Console.Out )。

 using System; using System.Collections.Generic; using System.IO; namespace RedirectToFile { class Program { static void Main(string[] args) { var buffer = new char[100]; var outputs = new List(); foreach (var file in args) outputs.Add(new StreamWriter(file)); outputs.Add(Console.Out); int bytesRead; do { bytesRead = Console.In.ReadBlock(buffer, 0, buffer.Length); outputs.ForEach(o => o.Write(buffer, 0, bytesRead)); } while (bytesRead == buffer.Length); outputs.ForEach(o => o.Close()); } } } 

我使用它将输出从MSBuild批处理文件重定向到磁盘, 同时仍然输出到控制台窗口。

 Usage: MSBuild [options] | RedirectToFile.exe MSBuildLog.txt 

也许是这样的?

 class Tee { private readonly string m_programPath; private readonly string m_logPath; private TextWriter m_writer; public Tee(string programPath, string logPath) { m_programPath = programPath; m_logPath = logPath; } public void Run() { using (m_writer = new StreamWriter(m_logPath)) { var process = new Process { StartInfo = new ProcessStartInfo(m_programPath) { RedirectStandardOutput = true, UseShellExecute = false } }; process.OutputDataReceived += OutputDataReceived; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); } } private void OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); m_writer.WriteLine(e.Data); } } 

这个答案应该可以帮助您在.NET中有效地重定向标准输出

PS我永远不确定是否链接到SO的另一个答案是答案或评论