2012-04-03 99 views
3

我試圖讀取一個控制檯的過程用下面的代碼的全部內容(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'工作正常,但只能獲得第一行,但我需要在該階段的控制檯的全部內容。

我該如何解決這個問題?

回答

5

我會嘗試使用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 
+0

我將如何實現這到我當前的代碼?我已經實施它的方式似乎根本不稱之爲事件。 – user1293575 2012-04-03 16:15:18

+0

增加了一個示例,沒有運行它,所以也許錯別字,也做了一些C#到VB的轉換,所以可能不是100%:-) – brendan 2012-04-03 18:26:35

+0

你會如何使用匿名函數? MSDN似乎暗示它不可能。 。 。 https://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 – 2015-11-24 17:09:39

3

「對於捕獲輸出和錯誤

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

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