Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.

Evento Process.ErrorDataReceived


Publicado: noviembre de 2016

Se produce cuando una aplicación escribe en su secuencia redirigida de StandardError.

Espacio de nombres:   System.Diagnostics
Ensamblado:  System (en System.dll)

Public Event ErrorDataReceived As DataReceivedEventHandler

The E:System.Diagnostics.Process.ErrorDataReceived event indicates that the associated process has written to its redirected P:System.Diagnostics.Process.StandardError stream.

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


The application that is processing the asynchronous output should call the M:System.Diagnostics.Process.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 


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

.NET Framework
Disponible desde 2.0
Volver al principio