Execute a command and get its output in vb.net

This article will tell us how to execute a command and get its output in vb.net with example source code.The command process will be executed silently and the output and the error streams will be captured back into the main program.

Here is the example source code to execute the command silently and get its output

The function accepts the process name, arguments and the output is captured in the variable strGoingOut which can be used to display the output. Below the source code, example usage of the function is also given.


Public Sub ExecuteProcessSilentlyAndGetOutput(ByVal strProcessName As String, ByVal strArgs As String, Optional ByRef strGoingOut As String = "")
        Try
            ' Also uses Sub strbldrOutputHandler(sendingProcess As Object, outLine As DataReceivedEventArgs)
            'Doesnt output a newline at te end or blank line in begining,just the process output,it has been tested
            ' Initialize the process and its StartInfo properties. 

            Dim myProcess As New Process()
            myProcess.StartInfo.FileName = strProcessName
            myProcess.StartInfo.Arguments = strArgs
            ' Set UseShellExecute to false for redirection.
            myProcess.StartInfo.UseShellExecute = False

            'myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized
            myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            myProcess.StartInfo.CreateNoWindow = True

            ' Redirect the standard output   
            ' Read the stream asynchronously using an event handler.
            myProcess.StartInfo.RedirectStandardOutput = True
            myProcess.StartInfo.RedirectStandardError = True
            strbldrOutput = New System.Text.StringBuilder()

            ' Set our event handler to asynchronously read the sort output. 
            AddHandler myProcess.OutputDataReceived, AddressOf strbldrOutputHandler

            ' Redirect standard input as well.  This stream 
            ' is used synchronously.
            'myProcess.StartInfo.RedirectStandardInput = True

            ' Start the process.
            myProcess.Start()

            '' Use a stream writer to synchronously write the sort input. 
            'Dim sortStreamWriter As StreamWriter = myProcess.StandardInput

            '' Start the asynchronous read of the sort output stream.
            myProcess.BeginOutputReadLine()
            'Dim strErrorTask = myProcess.StandardError.ReadToEndAsync MOODED THIS FOR >net4
            Dim strErrorTask = myProcess.StandardError.ReadToEnd
            Dim strError As String = strErrorTask

            '' Prompt the user for input text lines.  Write each 
            '' line to the redirected input stream of the sort command.
            'Console.WriteLine("Ready to sort up to 50 lines of text")

            'Dim inputText As String
            'Dim numInputLines As Integer = 0
            'Do
            '    Console.WriteLine("Enter a text line (or press the Enter key to stop):")

            '    inputText = Console.ReadLine()
            '    If Not String.IsNullOrEmpty(inputText) Then
            '        numInputLines += 1
            '        sortStreamWriter.WriteLine(inputText)
            '    End If
            'Loop While Not String.IsNullOrEmpty(inputText) AndAlso numInputLines < 50
            'Console.WriteLine("<end of input stream>")
            'Console.WriteLine()

            '' End the input stream to the sort command.
            'sortStreamWriter.Close()

            ' Wait for the sort process to write the sorted text lines.
            myProcess.WaitForExit()

            If Not strError.Equals("") Then
                strGoingOut = strError
            End If

            If Not String.IsNullOrEmpty(numOutputLines) Then
                '' Write the formatted and sorted output to the console.
                'Console.WriteLine(" Sort results = {0} sorted text line(s) ", _
                '                  numOutputLines)
                'Console.WriteLine("----------")
                'Console.WriteLine(strbldrOutput)
                strGoingOut = strGoingOut + strbldrOutput.ToString

                'AGAIN LETS CLOSE PROCESS

                myProcess.Close()
            Else
                'Console.WriteLine(" No input lines were sorted.")
                strGoingOut = "No Data Received"
                'AGAIN LETS CLOSE PROCESS
                If Not strError.Equals("") Then
                    strGoingOut = strError
                End If
                myProcess.Close()
            End If


        Catch ex As Exception
            MsgBox(ex.ToString, vbSystemModal)
            strGoingOut = "Fatal Error : Error Code : Execute Process Error in main class, Please email complete error to my email abcd@gmail.com"
        End Try

    End Sub

Example usage of the function to execute command cmd.exe and netsh to view the output which is the firewall state of windows.The variable strOut contains the output and can be used to display the output


ExecuteProcessSilentlyAndGetOutput("cmd.exe", "/c netsh advfirewall show publicprofile state", strOut)



That is all.

If you liked this article please do leave a reply and share it with friends.

Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.