VB.NET进程重定向输出不起作用

时间:2012-03-01 14:46:55

标签: vb.net shell command-line

我正在尝试从VB.NET中的命令行应用程序重定向输出,并且由于某种原因它无法重定向输出。这是我的代码:

    Dim myProcess As Process = New Process
    myProcess.StartInfo.FileName = "g++"
    myProcess.StartInfo.Arguments = CMDLineCommand
    myProcess.StartInfo.UseShellExecute = False
    myProcess.StartInfo.RedirectStandardOutput = True
    myProcess.StartInfo.RedirectStandardError = True
    myProcess.StartInfo.CreateNoWindow = True
    myProcess.Start()
    Dim output As String = myProcess.StandardOutput.ReadToEnd
    myProcess.WaitForExit()
    CMDLineOutputTextBox.Text = output

有人知道为什么没有重定向吗?提前谢谢!

-Neil

编辑:这是我的完整代码,以防我的语法有什么奇怪之处:<​​/ p>

        Dim myProcess As Process = New Process
        myProcess.StartInfo.FileName = "g++"
        myProcess.StartInfo.Arguments = CMDLineCommand
        myProcess.StartInfo.UseShellExecute = False
        myProcess.StartInfo.RedirectStandardOutput = True
        myProcess.StartInfo.RedirectStandardError = True
        myProcess.StartInfo.CreateNoWindow = True
        myProcess.EnableRaisingEvents = True
        AddHandler myProcess.OutputDataReceived, AddressOf GotData
        myProcess.Start()
        CMDLineOutputTextBox.Text = ""
        myProcess.BeginOutputReadLine()

稍后......

Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
        If Not String.IsNullOrEmpty(outLine.Data) Then
            SetText(outLine.Data)
        End If
End Sub

Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
    If Me.CMDLineOutputTextBox.InvokeRequired Then
        Dim d As New SetTextCallback(AddressOf SetText)
        Me.Invoke(d, New Object() {value})
    Else
        Me.CMDLineOutputTextBox.Text += value + Environment.NewLine
    End If
End Sub

有什么奇怪的吗?

2 个答案:

答案 0 :(得分:0)

您的方法将起作用,在您按下输出到最后输出的行的时间提供,所有输出都在那里。由于您使用的是g ++,我认为并非总是如此。您可能最好使用OutputDataReceived事件并从中捕获数据。

Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "ping"
myProcess.StartInfo.Arguments = "www.google.com"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True 
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
myProcess.BeginOutputReadLine()

然后你处理这样的事件:

Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
    If Not String.IsNullOrEmpty(outLine.Data) Then
        SetText(outLine.Data)
    End If
End Sub 

Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
    If Me.TextBox3.InvokeRequired Then
        Dim d As New SetTextCallback(AddressOf SetText)
        Me.Invoke(d, New Object() {value})
    Else
        Me.TextBox3.Text += value + Environment.NewLine
    End If
End Sub

答案 1 :(得分:0)

我注意到waitforExit似乎在invoke.required检查期间使代码锁定。当我拿出waitforexit时,它可以工作。