2010-08-31 27 views
0

这是windows-application-form的代码;我想要执行的批处理文件显示我通过RedirectStandardOutput = false;得到的shell屏幕上的输出,但我也希望输出被同时重定向到日志文件。为此,我使用RedirectStandardOutput = true;如何重定向输出以及同时获得shell屏幕上的输出

当然,一次只能使用一个!

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); 

回答

0

捕获输出并自己将其打印到屏幕上。这就是tee命令在大多数非Windows操作系统上满足这种需求的方式。在你的代码的某个地方

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(); 

而且有一个事件处理程序:

+0

这不是很有帮助,他/她显然是在使用Windows,因为他们正在写C:\ – codemonkeh 2010-08-31 04:47:42

+0

@codemonkeh:你认为我的第一句话本身更有用吗?我完全知道我们在这里与Windows打交道,这就是为什么我没有说“只使用'tee'”,但是该怎么做。事实上,在面向命令行的系统上执行POSIX标准化命令是一种常见的事情,这只是背景信息,有助于说服OP确信这是正确的方法。 – 2010-08-31 05:00:48

+0

我认为@ system-rule正在寻找一种特定的代码内解决方案,所以他们更喜欢一个例子。对不起,如果我冒犯了你。 – codemonkeh 2010-08-31 05:22:24

0

你可以尝试这样的事情从MSDN: Process.BeginOutputReadLine Method采取

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); 
    } 
} 

例。将文件保持为可写状态或甚至缓冲文件会更有效率,但这会使范例缩短。

+0

感谢您的良好响应我试过这个,但它dosent调用SortOutputHandler和创建文件(日志文件),但它给出了shell屏幕上的输出,当我改变这个p.StartInfo.RedirectStandardOutput = false; (true - > false) 我的问题仍然没有解决:( 我想要的东西,让我在屏幕上输出以及我可以得到一个文件的输出,以便我可以维护一个日志文件... – user434934 2010-08-31 08:23:28