2014-07-07 81 views
-1

我使用这个代码:从CMD读取输出异步

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输出和错误数据,但是,我m无法知道命令何时完成执行。我想知道什么时候它到达流的尽头,我抓住所有的输出,并用它做一些事情...

我一直在寻找相当长的时间,并且找不到答案这个。 请帮忙吗?

+0

使用'WaitForExit()',可能是 –

+0

我需要cmd继续运行,我需要运行更多的命令,并且每次关闭它都不符合我的需求......任何其他想法? – SomeNickName

+0

Downvote的原因是什么? – SomeNickName

回答

0

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

+0

感谢您的信息,我很害怕这个,应该有一些东西与BeginOutputReadline一起,可以告诉流达到了“结束”什么的,但我明白为什么现在......必须考虑另一种方式这个,谢谢。 – SomeNickName