vb.net – 读取控制台流程输出
发布时间:2020-12-17 07:23:54 所属栏目:百科 来源:网络整理
导读:我正在尝试使用以下代码读取控制台进程的全部内容(3秒后): Dim NewProcess As New System.Diagnostics.Process()With NewProcess.StartInfo .FileName = EXE_PATH .RedirectStandardOutput = True .RedirectStandardError = True .RedirectStandardInput =
我正在尝试使用以下代码读取控制台进程的全部内容(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’工作正常,但只获得第一行,但我需要在该阶段控制台的全部内容. 我怎么解决这个问题? 解决方法
我会尝试使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |