使用Process进行实时控制台输出重定向 [英] Realtime Console Output Redirection using Process

查看:52
本文介绍了使用Process进行实时控制台输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VBOXMANAGE导出"来宾计算机.VBOXManage是一个控制台应用程序,可以从主机控制来宾计算机的行为.由于导出命令是一个漫长的过程,因此它会返回过程更新,如下所示:

I am using VBOXMANAGE to "export" a guest machine. VBOXManage is a Console application that can control the guest machine's behavior from the host. Since the export command is a long process, it returns process updates like so:

0%... 10%... 20%... 30%... 100%

0%...10%...20%...30%...100%

我正在编写一个C#应用程序,它将使用Process调用VBOXManage.这是我的代码:

I am writing a C# application that will invoke VBOXManage using Process. Here's my code:

Process VBOXProc = new Process();

VBOXProc.StartInfo.FileName = VBOXMANAGE;
VBOXProc.StartInfo.Arguments = Arguments;
VBOXProc.StartInfo.UseShellExecute = false;
VBOXProc.StartInfo.CreateNoWindow = true;
VBOXProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
VBOXProc.StartInfo.RedirectStandardError = true;
VBOXProc.StartInfo.RedirectStandardOutput = true;

VBOXProc.OutputDataReceived += new DataReceivedEventHandler(VBOXProc_OutputDataReceived);
VBOXProc.ErrorDataReceived += new DataReceivedEventHandler(VBOXProc_ErrorDataReceived);

VBOXProc.EnableRaisingEvents = true;

VBOXProc.Start();
VBOXProc.BeginOutputReadLine();
VBOXProc.BeginErrorReadLine();

VBOXProc.WaitForExit();

这很好,除了按LINE读取输出.这意味着该过程会更新0%... 10%... 20%... 30%... 100%"将仅在实际过程完成后显示.

This is fine, except that the output is being read per LINE. This means that the process updates " 0%...10%...20%...30%...100%" will only show AFTER the actual process is done.

是否可以实时捕获控制台输出?

Is there a way to capture the console output in realtime?

谢谢!

推荐答案

这对我有用:

process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;

process.ErrorDataReceived += (sendingProcess, errorLine) => error.AppendLine(errorLine.Data);
process.OutputDataReceived += (sendingProcess, dataLine) => SetMessage(dataLine.Data);

process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();

process.WaitForExit();

error.AppendLine() SetMessage()是我使用的方法.

这篇关于使用Process进行实时控制台输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆