Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vb.net - Read Console Process Output

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)

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.

How can I solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would try using the Process.OutputDataReceived Event to read the output asyncronously.

See: 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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...