1

嗨,我需要使用 Visual Basic 将我发送到命令提示符的命令的响应捕获为字符串,我想在捕获后立即从字符串中读取。如果您在以下目录“C:\”中有一个名为 Pingfolder 的文件夹(例如示例 C:\Pingfolder)和该示例中的一个名为“ping.txt”的 txt 文件,则以下代码将起作用:您需要此 C:\Pingfolder\ping .txt 此代码将 ping 响应写入 ping.txt 文件。

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim NewProcess As New Process
        Dim StartInfoProcess As New System.Diagnostics.ProcessStartInfo
        StartInfoProcess.FileName = "cmd"
        StartInfoProcess.RedirectStandardInput = True
        StartInfoProcess.RedirectStandardOutput = True
        StartInfoProcess.UseShellExecute = False
        StartInfoProcess.CreateNoWindow = True
        NewProcess.StartInfo = StartInfoProcess
        NewProcess.Start()
        Dim SIOSW As System.IO.StreamWriter = NewProcess.StandardInput
        SIOSW.WriteLine("cd\")
        SIOSW.WriteLine("cd Pingfolder")
        SIOSW.WriteLine("ping www.google.com > ping.txt")
        SIOSW.WriteLine("Exit")
        SIOSW.Close()
    End Sub

在上面的代码中 SIOSW.WriteLine("ping www.google.com > ping.txt") ping www.google.com 然后将响应保存到 ping.txt"。在上面的代码中,我想将响应捕获为一个字符串而不是将其写入 ping.txt 文件。我需要这样的东西:

dim theresault as string
theresault = SIOSW.WriteLine("ping www.google.com")
messagebox.show(theresault)
4

2 回答 2

1

您需要在 NewProcess 上监听 OutputDataReceived 事件。

请参阅此处的文档:http: //msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx

于 2013-08-28T08:17:12.527 回答
0

以下允许我阅读对字符串的响应

     Dim thestring As String
   Dim SIOSR As System.IO.StreamReader = NewProcess.StandardOutput
    thestring = SIOSR.ReadToEnd

这是下面的代码完整代码这将发送命令并将响应保存为字符串,然后将其显示为消息

Dim NewProcess As New Process
Dim StartInfoProcess As New System.Diagnostics.ProcessStartInfo
Dim thestring As String
StartInfoProcess.FileName = "cmd"
StartInfoProcess.RedirectStandardInput = True
StartInfoProcess.RedirectStandardOutput = True
StartInfoProcess.UseShellExecute = False
StartInfoProcess.CreateNoWindow = True
NewProcess.StartInfo = StartInfoProcess
NewProcess.Start()
Dim SIOSW As System.IO.StreamWriter = NewProcess.StandardInput
Dim SIOSR As System.IO.StreamReader = NewProcess.StandardOutput
SIOSW.WriteLine("ping www.google.com")
Threading.Thread.Sleep(15000)
SIOSW.WriteLine("Exit")
thestring = SIOSR.ReadToEnd
    MessageBox.Show(thestring)
SIOSW.Close()
SIOSR.Close()
于 2013-08-28T08:33:58.037 回答