【问题标题】:Read Console Process Output读取控制台进程输出
【发布时间】:2012-04-03 15:39:46
【问题描述】:

我正在尝试使用以下代码读取控制台进程的全部内容(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' 工作正常,但只获取第一行,但在那个阶段我需要控制台的全部内容。

我该如何解决这个问题?

【问题讨论】:

    标签: vb.net string console


    【解决方案1】:

    我会尝试使用 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 
    

    【讨论】:

    • 如何在我当前的代码中实现这一点?我实现它的方式似乎根本没有调用事件。
    • 添加了一个示例,没有运行它所以可能是拼写错误,还在我的脑海中做了一些 c# 到 vb 的转换,所以可能不是 100% :-)
    • 如何使用匿名函数? MSDN 似乎暗示这是不可能的。 . . msdn.microsoft.com/en-us/library/…
    【解决方案2】:

    '用于捕获输出和错误

        AddHandler NewProcess.OutputDataReceived, AddressOf OutputHandler
        AddHandler NewProcess.ErrorDataReceived, AddressOf OutputHandler
    
        NewProcess.Start()
        NewProcess.BeginOutputReadLine()
        NewProcess.BeginErrorReadLine()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多