C# 如何重定向输出以及同时在shell屏幕上获取输出
这是windows应用程序窗体代码;我希望将要执行的批处理文件在shell屏幕上显示我通过C# 如何重定向输出以及同时在shell屏幕上获取输出,c#,C#,这是windows应用程序窗体代码;我希望将要执行的批处理文件在shell屏幕上显示我通过RedirectStandardOutput=false获得的输出,但我还希望同时将输出重定向到日志文件。为此,我使用RedirectStandardOutput=true 当然,一次只能使用一个 System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "c:\test\build.ba
RedirectStandardOutput=false获得的输出代码>,但我还希望同时将输出重定向到日志文件。为此,我使用RedirectStandardOutput=true代码>
当然,一次只能使用一个
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);
捕获输出并自己将其打印到屏幕上。这就是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();
并且在代码中的某个地方有一个事件处理程序:
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);
}
}
例子取自。保持文件的打开是有效的,甚至是为了缓冲它,但这会使示例保持简短。这不是很有帮助,他/她显然是在使用Windows来写C:\@ COMDENKEH:你认为我的第一句话本身更有帮助吗?我完全知道我们在这里处理的是Windows,这就是为什么我没有说“只使用tee
”,而是说该怎么做。事实上,在面向命令行的系统上,POSIX标准化一个命令只是一个背景信息,可以帮助OP相信这是正确的方法。我认为@system rule正在寻找一个特定的代码内解决方案,所以他们更喜欢一个例子。如果我冒犯了你,很抱歉。谢谢你的回复,我尝试了这个,但它没有调用SortoutPurtHandler和nither创建文件(logfile),但当我更改此p.StartInfo.RedirectStandardOutput=false时,它会在shell屏幕上给出输出;(true->false)我的问题仍然没有解决:(我想要在屏幕上显示输出的东西,并且我可以在文件中获得输出,这样我就可以维护一个日志文件。。。