如何从cmd shell中读取VB.NET中的cmd输出?

时间:2011-06-18 16:46:07

标签: vb.net cmd gnokii

我正在使用gnokii发送短信。

我的VB代码:

Dim xCmd As String
xCmd = "cmd.exe /c echo msgcontent "| c:\gnokii\gnokii.exe --sendsms 12345678"
Shell(xCmd)

注意事项:

  1. 我尝试将输出重定向到.txt文件,但.txt文件似乎为空。此外,程序可能必须每秒发送多个SMS,因此创建.txt是不可行的。

  2. Process.Start()不可行,因为我必须检查gnokii.exe是否正在运行。

  3. 我需要输出来检查SMS是否成功发送。

  4. 我尝试使用(下面的代码),但它也没有用;没有显示输出。

    函数exe(ByVal fileName,ByVal args)

    Dim p As Process = New Process
    Dim output As String
    
    With p
        .StartInfo.CreateNoWindow = True
        .StartInfo.UseShellExecute = False
        .StartInfo.RedirectStandardOutput = True
        .StartInfo.FileName = fileName
        .StartInfo.Arguments = args
        .Start()
        output = .StandardOutput.ReadToEnd
    End With
    
    Return output
    

    结束职能

4 个答案:

答案 0 :(得分:2)

试试这个:

    Dim p As Process = New Process
    Dim output As String

    With p
        .StartInfo.CreateNoWindow = True
        .StartInfo.RedirectStandardOutput = True
        .StartInfo.UseShellExecute = False
        .StartInfo.FileName = fileName
        .StartInfo.Arguments = args
        .Start()
        output = .StandardOutput.ReadToEnd
        .WaitForExit()
    End With

    Return output

答案 1 :(得分:1)

将输出发送到.txt文件(我能找到的最佳解决方案)

更换

xCmd = "cmd.exe /c echo msgcontent "| c:\gnokii\gnokii.exe --sendsms 12345678 > file.txt"

使用

xCmd = "cmd.exe /c echo msgcontent "| c:\gnokii\gnokii.exe --sendsms 12345678 2> file.txt"

答案 2 :(得分:0)

您可以使用此100%作品,但它只会显示结果

如何在vb.net中显示shell结果:

'create 1 textbox1
'create 1 button1
'create 1 richtextbox1
'in the start up directory of this program make a file could 123.text
'------------------------------------------------------------------------
Dim read As System.IO.StreamReader
read = File.OpenText(Application.StartupPath & "\123.text")

Shell("cmd.exe /c" & TextBox1.Text + ">123.text")
Do Until read.EndOfStream
    RichTextBox1.Text = read.ReadLine & vbCrLf
Loop
'--------------------------------------------------------------------------
'you can add on the top to create the file if it does not exists,   

If IO.File.Exists(Application.StartupPath & "\123.text") = False Then
    IO.File.Create(Application.StartupPath & "\123.text")
End If
'-------------------------------------------------------------------------

此链接http://pastebin.com/iEhv61jG

也提供了该代码

答案 3 :(得分:0)

我可能会建议这样的事情,我自己。这与其他人发布的内容类似,但我认为它提供了更多功能。

Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Shell("cmd.exe /c " & TextBox1.Text + " > c:\temp\output.txt")
    Dim read As System.IO.StreamReader
    read = File.OpenText("c:\temp\output.txt")
    RichTextBox1.Clear()
    Do Until read.EndOfStream
        RichTextBox1.Text += read.ReadLine & vbCrLf
    Loop
    RichTextBox1.Select(RichTextBox1.Text.Length, 0)
    RichTextBox1.ScrollToCaret()
End Sub
End Class