读取控制台进程输出 [英] Read Console Process Output
问题描述
我尝试用以下代码读取控制台进程的全部内容(3秒后):
I'm attempting to read the full contents of a console process (after 3 seconds) with the code below:
Dim NewProcess As New System.Diagnostics.Process()
With NewProcess.StartInfo
.FileName = EXE_PATH
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With
NewProcess.Start()
System.Threading.Thread.Sleep(3000)
MsgBox(NewProcess.StandardOutput.ReadToEnd)
但是,当尝试'ReadToEnd'时,应用程序似乎暂停,我认为这是因为控制台进程是一个连续的输出,并且永远不会实际结束。 'ReadLine'工作正常,但只有第一行,但我需要控制台的整个内容在那个阶段。
However, the application seems to pause when attempting to 'ReadToEnd', I think this is because the console process is a continuous output and is never going to actually end. 'ReadLine' works fine, but only gets the first line, but I need the entire contents of the console at that stage.
我如何解决这个问题? p>
How can I solve this problem?
推荐答案
我会尝试使用Process.OutputDataReceived事件来异步读取输出。
I would try using the Process.OutputDataReceived Event to read the output asyncronously.
请参阅: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx#Y242
Private Shared processOutput As StringBuilder = Nothing
Public Shared Sub StartSomeProcess()
processOutput = new StringBuilder()
Dim NewProcess As New System.Diagnostics.Process()
With NewProcess.StartInfo
.FileName = EXE_PATH
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With
' Set our event handler to asynchronously read the sort output.
AddHandler NewProcess.OutputDataReceived, AddressOf OutputHandler
NewProcess.Start()
NewProcess.BeginOutputReadLine()
NewProcess.WaitForExit()
MsgBox(processOutput.ToString())
End Sub
Private Shared Sub OutputHandler(sendingProcess As Object, outLine As DataReceivedEventArgs)
' Collect the sort command output.
If Not String.IsNullOrEmpty(outLine.Data) Then
' Add the text to the collected output.
processOutput.AppendLine(outLine.Data)
End If
End Sub
这篇关于读取控制台进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!