开发者

how to redirect the output as well as get the output on shell screen at same time

This is windows-application-form code; I want the batch file which is going to be executed to show the output on shell screen which I got by RedirectStandardOutput = false;, but I also want output to be redirected to a log file at the same time. For this, I use 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.UseShellExec开发者_运维技巧ute = 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.


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. It would be more efficient to keep the file open for writing, or even to buffer it but this keeps the example short.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜