从cmd异步读取输出

时间:2014-07-07 20:28:00

标签: vb.net

我正在使用此代码:

Shared sb_OutputData As New StringBuilder()
Shared sb_ErrorData As New StringBuilder()
Shared proc As Process = Nothing

Private Sub cmd()
    If proc IsNot Nothing Then
        Exit Sub
    End If

    Dim info As New ProcessStartInfo("cmd.exe")

    ' Redirect the standard output of the process.

    info.RedirectStandardOutput = True
    info.RedirectStandardInput = True
    info.RedirectStandardError = True

    ' Set UseShellExecute to false for redirection

    info.UseShellExecute = False
    proc = New Process
    proc.StartInfo = info

    ' Set our event handler to asynchronously read the sort output.

    AddHandler proc.OutputDataReceived, AddressOf proc_OutputDataReceived
    AddHandler proc.ErrorDataReceived, AddressOf proc_ErrorDataReceived

    proc.Start()

    ' Start the asynchronous read of the sort output stream. Note this line!
    proc.BeginOutputReadLine()
    proc.BeginErrorReadLine()

End Sub

Private Shared Sub proc_ErrorDataReceived(sender As Object, e As DataReceivedEventArgs)
    'Console.WriteLine("Error data: {0}", e.Data)
    sb_ErrorData.AppendLine(e.Data)
End Sub

Private Shared Sub proc_OutputDataReceived(sender As Object, e As DataReceivedEventArgs)
    '   Console.WriteLine("Output data: {0}", e.Data)
    sb_OutputData.AppendLine(e.Data)
End Sub

Sub CmdWrite(arguments As String)
    Dim writeStream As StreamWriter = proc.StandardInput
    writeStream.WriteLine(arguments)
End Sub

它完全按照我的意愿工作,能够检索cmd输出和错误数据而不关闭它(并且异步),但是,我无法知道命令何时完成执行。我想知道它什么时候到达流的末尾让我抓住所有输出并用它做点什么...

我一直在寻找很长时间,但无法找到答案。 请帮忙吗?

1 个答案:

答案 0 :(得分:0)

只要命令窗口打开,流就会打开。你无法判断他们何时停止或开始。如果您正在运行的命令没有以唯一/可检测的模式指示其结束,那么您将被卡住,除非您可以编辑正在运行的脚本并插入字符串 - 您无法保证不会显示该字符串在正常输出中 - 在命令调用之间。

相关问题