[英]how to redirect the output as well as get the output on shell screen at same time
This is windows-application-form code; 这是Windows应用程序形式的代码; I want the batch file which is going to be executed to show the output on shell screen which I got by
RedirectStandardOutput = false;
我想要批处理文件,该文件将被执行以在由
RedirectStandardOutput = false;
获得的外壳屏幕上显示输出RedirectStandardOutput = false;
, but I also want output to be redirected to a log file at the same time. ,但我也希望同时将输出重定向到日志文件。 For this, I use
RedirectStandardOutput = true;
为此,我使用
RedirectStandardOutput = true;
. 。
Of course, only one can be used at one time! 当然一次只能使用一个!
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "c:\test\build.bat";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true; // if I use false all the commented lines below are not applicable for comments
p.Start();
string output = null;
//try
//{
output = p.StandardOutput.ReadToEnd();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.ToString());
//}
System.IO.File.WriteAllText("c:\test\log.txt", output);
Capture the output and print it to the screen yourself. 捕获输出并自己将其打印到屏幕上。 That's how the
tee
command meets this need on most non-Windows operating systems. 这就是
tee
命令在大多数非Windows操作系统上满足此需求的方式。
You could try something like this: 您可以尝试这样的事情:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "c:\test\build.bat";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
p.Start();
And have an event handler somewhere in your code: 并在代码中的某个位置添加事件处理程序:
private static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
Console.WriteLine(outLine.Data);
System.IO.File.AppendAllText("c:\test\log.txt", outLine.Data);
}
}
Example taken from MSDN: Process.BeginOutputReadLine Method . 取自MSDN的示例:Process.BeginOutputReadLine方法 。 It would be more efficient to keep the file open for writing, or even to buffer it but this keeps the example short.
保持打开状态以供写入或缓冲文件的效率更高,但这使示例简短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.