ErrorDataReceived Event
Collapse the table of content
Expand the table of content

Process.ErrorDataReceived Event

Occurs when an application writes to its redirected StandardError stream.

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

<BrowsableAttribute(True)> _
Public Event ErrorDataReceived As DataReceivedEventHandler

The ErrorDataReceived event indicates that the associated process has written to its redirected StandardError stream.

The event only occurs during asynchronous read operations on StandardError. To start asynchronous read operations, you must redirect the StandardError stream of a Process, add your event handler to the ErrorDataReceived event, and call BeginErrorReadLine. Thereafter, the ErrorDataReceived event signals each time the process writes a line to the redirected StandardError stream, until the process exits or calls CancelErrorRead.


The application that is processing the asynchronous output should call the WaitForExit method to ensure that the output buffer has been flushed.

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 

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

  • LinkDemand 

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

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

© 2015 Microsoft