读取控制台进程输出

5
我正在尝试使用以下代码读取控制台进程的全部内容(3秒后):

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'可以正常工作,但只能获取第一行,而我需要在那个阶段获取整个控制台的内容。

我该如何解决这个问题?

2个回答

7
我会尝试使用Process.OutputDataReceived事件异步读取输出。请参阅: 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 

我该如何将这个实现到我的当前代码中?我已经实现了,但似乎根本没有调用事件。 - user1293575
添加了一个示例,还没有运行,可能会有拼写错误,同时在脑海中进行一些C#到VB的转换,所以可能不是100%正确 :-) - brendan

4

'用于捕获输出和错误信息'

    AddHandler NewProcess.OutputDataReceived, AddressOf OutputHandler
    AddHandler NewProcess.ErrorDataReceived, AddressOf OutputHandler

    NewProcess.Start()
    NewProcess.BeginOutputReadLine()
    NewProcess.BeginErrorReadLine()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接