Process.BeginErrorReadLine Method ()


Begins asynchronous read operations on the redirected StandardError stream of the application.

Namespace:   System.Diagnostics
Assembly:  System (in System.dll)

Public Sub BeginErrorReadLine

Exception Condition

The ProcessStartInfo.RedirectStandardError property is false.

- or -

An asynchronous read operation is already in progress on the StandardError stream.

- or -

The StandardError stream has been used by a synchronous read operation.

The StandardError stream can be read synchronously or asynchronously. Methods such as Read, ReadLine, and ReadToEnd perform synchronous read operations on the error output stream of the process. These synchronous read operations do not complete until the associated Process writes to its StandardError stream, or closes the stream.

In contrast, BeginErrorReadLine starts asynchronous read operations on the StandardError stream. This method enables the designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.

Follow these steps to perform asynchronous read operations on StandardError for a Process :

  1. Set UseShellExecute to false.

  2. Set RedirectStandardError to true.

  3. Add your event handler to the ErrorDataReceived event. The event handler must match the System.Diagnostics.DataReceivedEventHandler delegate signature.

  4. Start the Process.

  5. Call BeginErrorReadLine for the Process. This call starts asynchronous read operations on StandardError.

When asynchronous read operations start, the event handler is called each time the associated Process writes a line of text to its StandardError stream.

You can cancel an asynchronous read operation by calling CancelErrorRead. The read operation can be canceled by the caller or by the event handler. After canceling, you can call BeginErrorReadLine again to resume asynchronous read operations.


You cannot mix asynchronous and synchronous read operations on a redirected stream. Once the redirected stream of a Process is opened in either asynchronous or synchronous mode, all further read operations on that stream must be in the same mode. For example, do not follow BeginErrorReadLine with a call to ReadLine on the StandardError stream, or vice versa. However, you can read two different streams in different modes. For example, you can call BeginErrorReadLine and then call ReadLine for the StandardOutput stream.

The following example uses the net view command to list the available network resources on a remote computer. The user supplies the target computer name as a command-line argument. The user can also supply a file name for error output. The example collects the output of the net command, waits for the process to finish, and then writes the output results to the console. If the user supplies the optional error file, the example writes errors to the file.

' Define the namespaces used by this sample.
Imports System
Imports System.Text
Imports System.Globalization
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Namespace ProcessAsyncStreamSamples

   Class ProcessAsyncErrorRedirection
      ' Define static variables shared by class methods.
      Private Shared streamError As StreamWriter = Nothing
      Private Shared netErrorFile As String = ""
      Private Shared netOutput As StringBuilder = Nothing
      Private Shared errorRedirect As Boolean = False
      Private Shared errorsWritten As Boolean = False

      Public Shared Sub RedirectNetCommandStreams()
         Dim netArguments As String
         Dim netProcess As Process

         ' Get the input computer name.
         Console.WriteLine("Enter the computer name for the net view command:")
         netArguments = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture)
         If String.IsNullOrEmpty(netArguments) Then
            ' Default to the help command if there is 
            ' not an input argument.
            netArguments = "/?"
         End If

         ' Check if errors should be redirected to a file.
         errorsWritten = False
         Console.WriteLine("Enter a fully qualified path to an error log file")
         Console.WriteLine("  or just press Enter to write errors to console:")
         netErrorFile = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture)
         If Not String.IsNullOrEmpty(netErrorFile) Then
            errorRedirect = True
         End If

         ' Note that at this point, netArguments and netErrorFile
         ' are set with user input.  If the user did not specify
         ' an error file, then errorRedirect is set to false.

         ' Initialize the process and its StartInfo properties.
         netProcess = New Process()
         netProcess.StartInfo.FileName = "Net.exe"

         ' Build the net command argument list.
         netProcess.StartInfo.Arguments = String.Format("view {0}", _

         ' Set UseShellExecute to false for redirection.
         netProcess.StartInfo.UseShellExecute = False

         ' Redirect the standard output of the net command.  
         ' Read the stream asynchronously using an event handler.
         netProcess.StartInfo.RedirectStandardOutput = True
         AddHandler netProcess.OutputDataReceived, _
                            AddressOf NetOutputDataHandler
         netOutput = new StringBuilder()

         If errorRedirect Then
            ' Redirect the error output of the net command. 
            netProcess.StartInfo.RedirectStandardError = True
            AddHandler netProcess.ErrorDataReceived, _
                            AddressOf NetErrorDataHandler
            ' Do not redirect the error output.
            netProcess.StartInfo.RedirectStandardError = False
         End If

         Console.WriteLine(ControlChars.Lf + "Starting process: NET {0}", _
         If errorRedirect Then
            Console.WriteLine("Errors will be written to the file {0}", _
         End If

         ' Start the process.

         ' Start the asynchronous read of the standard output stream.

         If errorRedirect Then
            ' Start the asynchronous read of the standard
            ' error stream.
         End If

         ' Let the net command run, collecting the output.

         If Not streamError Is Nothing Then
             ' Close the error file.
             ' Set errorsWritten to false if the stream is not
             ' open.   Either there are no errors, or the error
             ' file could not be opened.
             errorsWritten = False
         End If

         If netOutput.Length > 0 Then
            ' If the process wrote more than just
            ' white space, write the output to the console.
            Console.WriteLine("Public network shares from net view:")
         End If

         If errorsWritten Then
            ' Signal that the error file had something 
            ' written to it.
            Dim errorOutput As String()
            errorOutput = File.ReadAllLines(netErrorFile)
            If errorOutput.Length > 0 Then

                Console.WriteLine(ControlChars.Lf + _
                    "The following error output was appended to {0}.", _
                Dim errLine as String
                For Each errLine in errorOutput
                    Console.WriteLine("  {0}", errLine)

            End If
         End If

      End Sub 

      Private Shared Sub NetOutputDataHandler(sendingProcess As Object, _
          outLine As DataReceivedEventArgs)

         ' Collect the net view command output.
         If Not String.IsNullOrEmpty(outLine.Data) Then
            ' Add the text to the collected output.
            netOutput.Append(Environment.NewLine + "  " + outLine.Data)
         End If
      End Sub 

      Private Shared Sub NetErrorDataHandler(sendingProcess As Object, _
          errLine As DataReceivedEventArgs)

         ' Write the error text to the file if there is something to
         ' write and an error file has been specified.

         If Not String.IsNullOrEmpty(errLine.Data) Then

            If Not errorsWritten Then
                If streamError Is Nothing Then
                    ' Open the file.
                        streamError = New StreamWriter(netErrorFile, true)
                    Catch e As Exception
                        Console.WriteLine("Could not open error file!")
                    End Try
                End If

                If Not streamError Is Nothing Then

                    ' Write a header to the file if this is the first
                    ' call to the error output handler.
                    streamError.WriteLine("Net View error output:")

                End If

                errorsWritten = True
            End If

            If Not streamError Is Nothing Then

                ' Write redirected errors to the file.
             End If
          End If
      End Sub 
   End Class  
End Namespace 


for full trust for the immediate caller. This member cannot be used by partially trusted code.

.NET Framework
Available since 2.0
Return to top