该 C# 示例很糟糕,因为它没有显示如何实际读取标准输出流。创建一个这样的方法:
Public Function ExecuteCommand(ByVal filePath As String, ByVal arguments As String) As String
Dim p As Process
p = New Process()
p.StartInfo.FileName = filePath
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardOutput = True
p.Start()
p.WaitForExit()
Return p.StandardOutput.ReadToEnd()
End Function
然后你可以这样称呼它:
Dim output As String = ExecuteCommand("mycommand.exe", "")
当然,这会进行同步调用。如果您希望它异步调用命令行并在完成时引发一个事件,这也是可能的,但需要更多的编码。
例如,如果您想异步执行此操作,并且只是在固定时间间隔内定期检查更多输出,那么这是一个简单的示例:
Public Class CommandExecutor
Implements IDisposable
Public Event OutputRead(ByVal output As String)
Private WithEvents _process As Process
Public Sub Execute(ByVal filePath As String, ByVal arguments As String)
If _process IsNot Nothing Then
Throw New Exception("Already watching process")
End If
_process = New Process()
_process.StartInfo.FileName = filePath
_process.StartInfo.UseShellExecute = False
_process.StartInfo.RedirectStandardInput = True
_process.StartInfo.RedirectStandardOutput = True
_process.Start()
_process.BeginOutputReadLine()
End Sub
Private Sub _process_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles _process.OutputDataReceived
If _process.HasExited Then
_process.Dispose()
_process = Nothing
End If
RaiseEvent OutputRead(e.Data)
End Sub
Private disposedValue As Boolean = False
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If _process IsNot Nothing Then
_process.Kill()
_process.Dispose()
_process = Nothing
End If
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
然后你可以像这样使用它:
Public Class Form1
Private WithEvents _commandExecutor As New CommandExecutor()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
_commandExecutor.Execute("D:\Sandbox\SandboxSolution\ConsoleCs\bin\Debug\ConsoleCs.exe", "")
End Sub
Private Sub _commandExecutor_OutputRead(ByVal output As String) Handles _commandExecutor.OutputRead
Me.Invoke(New processCommandOutputDelegate(AddressOf processCommandOutput), output)
End Sub
Private Delegate Sub processCommandOutputDelegate(ByVal output As String)
Private Sub processCommandOutput(ByVal output As String)
TextBox1.Text = output
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
_commandExecutor.Dispose()
End Sub
End Class