Visual Basic Code Snippet - Execute Shell Commands from .Net

Visual Basic Code Snippet - Execute Shell Commands from .Net

Visual Basic Code Snippet - Execute Shell Commands from .Net

(VB) Visual Basic code snippet creates a command process and then invokes the command that we want to execute. The result of the command and any errors occurred during execution is stored in a string variables. This is a great method to execute your DOS commands from .Net.

Bookmark:

Visual Basic Code Snippet - Execute Shell Commands from .Net

This .Net Visual Basic code snippet executes a shell command. To use this function simply provide the file/command to execute, command line parameters (optional), string variable to store output and string variable to store errors occurred during execution.

The code creates a command process and then invokes the command that we want to execute. The result of the command and any errors occurred during execution is stored in a string variables, which can then be used for further reference. This is a great method to execute your DOS commands from .Net.

''' <summary>
''' Execute a shell command
''' </summary>
''' <param name="_FileToExecute">File/Command to execute</param>
''' <param name="_CommandLine">Command line parameters to pass</param> 
''' <param name="_outputMessage">returned string value after executing shell command</param> 
''' <param name="_errorMessage">Error messages generated during shell execution</param> 
Public Sub ExecuteShellCommand(ByVal _FileToExecute As String, ByVal _CommandLine As String, ByRef _outputMessage As String, ByRef _errorMessage As String)
    ' Set process variable
    ' Provides access to local and remote processes and enables you to start and stop local system processes.
    Dim _Process As System.Diagnostics.Process = Nothing
    Try
        _Process = New System.Diagnostics.Process()

        ' invokes the cmd process specifying the command to be executed.
        Dim _CMDProcess As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\cmd.exe", New Object() { Environment.SystemDirectory })

        ' pass executing file to cmd (Windows command interpreter) as a arguments
        ' /C tells cmd that we want it to execute the command that follows, and then exit.
        Dim _Arguments As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", New Object() { _FileToExecute })

        ' pass any command line parameters for execution
        If _CommandLine IsNot Nothing AndAlso _CommandLine.Length > 0 Then
            _Arguments &= String.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", New Object() { _CommandLine, System.Globalization.CultureInfo.InvariantCulture })
        End If

        ' Specifies a set of values used when starting a process.
        Dim _ProcessStartInfo As New System.Diagnostics.ProcessStartInfo(_CMDProcess, _Arguments)
        ' sets a value indicating not to start the process in a new window. 
        _ProcessStartInfo.CreateNoWindow = True
        ' sets a value indicating not to use the operating system shell to start the process. 
        _ProcessStartInfo.UseShellExecute = False
        ' sets a value that indicates the output/input/error of an application is written to the Process.
        _ProcessStartInfo.RedirectStandardOutput = True
        _ProcessStartInfo.RedirectStandardInput = True
        _ProcessStartInfo.RedirectStandardError = True
        _Process.StartInfo = _ProcessStartInfo

        ' Starts a process resource and associates it with a Process component.
        _Process.Start()

        ' Instructs the Process component to wait indefinitely for the associated process to exit.
        _errorMessage = _Process.StandardError.ReadToEnd()
        _Process.WaitForExit()

        ' Instructs the Process component to wait indefinitely for the associated process to exit.
        _outputMessage = _Process.StandardOutput.ReadToEnd()
        _Process.WaitForExit()
    Catch _Win32Exception As Win32Exception
        ' Error
        Console.WriteLine("Win32 Exception caught in process: {0}", _Win32Exception.ToString())
    Catch _Exception As Exception
        ' Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
    Finally
        ' close process and do cleanup
        _Process.Close()
        _Process.Dispose()
        _Process = Nothing
    End Try
End Sub


Here is a simple example showing how to use above function (ExecuteShellCommand) to execute a simple DOS dir command and show output result in a richtextbox.

Dim _Output As String = Nothing
Dim _Error As String = Nothing

ExecuteShellCommand("dir", "c:\", _Output, _Error)

richTextBox1.Text = _Output


This example shows how to use above method to execute DOS del command to delete all the ZIP files in c:\temp folder using .Net.
/F - Force deleting of read-only files.
/Q - Quiet mode, do not ask if ok to delete on global wildcard.

Dim _Output As String = Nothing
Dim _Error As String = Nothing

ExecuteShellCommand("del", "/F /Q c:\temp\*.zip", _Output, _Error)


VB Keywords Used:

  • Process
  • Format
  • ProcessStartInfo
  • Environment
  • SystemDirectory
  • InvariantCulture
  • Win32Exception
  • Exception

Code Snippet Information:

  • Applies To: .Net, VB, Visual Basic, CLI, Shell Execute from .Net, DOS, System Processes, Execute DOS Commands from .Net, Redirect Standard Output, Windows command interpreter
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment