将DOS命令响应捕获到字符串中

时间:2013-08-28 07:52:00

标签: vb.net string

我需要使用visual basic捕获我发送到命令提示符的命令的响应, 我想在捕获后尽快读取字符串。 如果在以下目录“C:\”中有一个名为Pingfolder的文件夹,则以下代码将起作用:egsample C:\ Pingfolder和一个名为“ping.txt”的txt文件,例如:你需要这个C:\ Pingfolder \ ping 。文本 此代码将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)

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

以下内容允许我阅读对字符串的回复

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

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

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()