从 VB.NET 执行 dos 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16170141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:22:20  来源:igfitidea点击:

Executing dos command from VB.NET

.netvb.netdos

提问by asim-ishaq

I need to execute an external process from VB.NET application, usually I run this process from command prompt:

我需要从 VB.NET 应用程序执行一个外部进程,通常我从命令提示符运行这个进程:

c:\> net.exe use \192.168.0.5\ipc$

When this command is executed, it displays a string like "The connection is successfull" OR "Access Denied" or any other relevant message.

执行此命令时,它会显示一个字符串,如“连接成功”或“访问被拒绝”或任何其他相关消息。

I need to execute this command from vb.net and as well can I capture the output string?

我需要从 vb.net 执行这个命令,我也可以捕获输出字符串吗?

回答by Hiren Pandya

Try below code, it will take your command as argument and print the output in the textbox.

尝试下面的代码,它会将您的命令作为参数并在文本框中打印输出。

Imports System.Diagnostics

Public Class frmConsoleDemo

Friend WithEvents txtConsoleOut As System.Windows.Forms.TextBox
Friend WithEvents txtConsoleIn As System.Windows.Forms.TextBox

Private psi As ProcessStartInfo
Private cmd As Process
Private Delegate Sub InvokeWithString(ByVal text As String)

Private Sub frmConsoleDemo_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    psi = New ProcessStartInfo("cmd.exe")

    Dim systemencoding As System.Text.Encoding = _
        System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)

    With psi
        .UseShellExecute = False  ' Required for redirection
        .RedirectStandardError = True
        .RedirectStandardOutput = True
        .RedirectStandardInput = True
        .CreateNoWindow = True
        .StandardOutputEncoding = systemencoding  ' Use OEM encoding for console applications
        .StandardErrorEncoding = systemencoding
    End With

    ' EnableraisingEvents is required for Exited event
    cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}

    AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
    AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
    AddHandler cmd.Exited, AddressOf CMD_Exited

    cmd.Start()
    ' Start async reading of the redirected streams
    ' Without these calls the events won't fire
    cmd.BeginOutputReadLine()
    cmd.BeginErrorReadLine()

    Me.txtConsoleIn.Select()
End Sub

Private Sub CMD_Exited(ByVal sender As Object, ByVal e As EventArgs)
    Me.Close()
End Sub

' This sub gets called in a different thread so invokation is required
Private Sub Async_Data_Received(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    Me.Invoke(New InvokeWithString(AddressOf Sync_Output), e.Data)
End Sub

Private Sub Sync_Output(ByVal text As String)
    txtConsoleOut.AppendText(text & Environment.NewLine)
    txtConsoleOut.ScrollToCaret()
End Sub

' Sending console commands here
Private Sub txtConsoleIn_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtConsoleIn.KeyPress
    If e.KeyChar = ControlChars.Cr Then
        cmd.StandardInput.WriteLine(txtConsoleIn.Text)
        txtConsoleIn.Clear()
    End If
End Sub

' Two text boxes called txtConsoleOut and txtConsoleIn
Public Sub New()
    Me.txtConsoleOut = New System.Windows.Forms.TextBox()
    Me.txtConsoleIn = New System.Windows.Forms.TextBox()
    Me.SuspendLayout()
    '
    'txtConsoleOut
    '
    Me.txtConsoleOut.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                Or System.Windows.Forms.AnchorStyles.Left) _
                Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
    Me.txtConsoleOut.Location = New System.Drawing.Point(12, 12)
    Me.txtConsoleOut.Multiline = True
    Me.txtConsoleOut.Name = "txtConsoleOut"
    Me.txtConsoleOut.ReadOnly = True
    Me.txtConsoleOut.ScrollBars = System.Windows.Forms.ScrollBars.Both
    Me.txtConsoleOut.Size = New System.Drawing.Size(665, 494)
    Me.txtConsoleOut.TabIndex = 0
    '
    'txtConsoleIn
    '
    Me.txtConsoleIn.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
                Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
    Me.txtConsoleIn.Location = New System.Drawing.Point(10, 512)
    Me.txtConsoleIn.Name = "txtConsoleIn"
    Me.txtConsoleIn.Size = New System.Drawing.Size(667, 20)
    Me.txtConsoleIn.TabIndex = 1
    '
    'frmConsoleDemo
    '
    Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
    Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
    Me.ClientSize = New System.Drawing.Size(689, 544)
    Me.Controls.Add(Me.txtConsoleIn)
    Me.Controls.Add(Me.txtConsoleOut)
    Me.Name = "frmConsoleDemo"
    Me.Text = "Console redirect demo"
    Me.ResumeLayout(False)
    Me.PerformLayout()

End Sub

End Class

Hope it helps..

希望能帮助到你..

回答by Joe

You can use the Processclass to start an external process in this way.

您可以使用Process类以这种方式启动外部进程。

To capture its output, read the Process.StandardOutputand/or Process.StandardErrorstreams.

要捕获其输出,请读取Process.StandardOutput和/或Process.StandardError流。