Export (0) Print
Expand All

DataReceivedEventArgs Class

Provides data for the OutputDataReceived and ErrorDataReceived events.

System.Object
  System.EventArgs
    System.Diagnostics.DataReceivedEventArgs

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

'Declaration
Public Class DataReceivedEventArgs _
	Inherits EventArgs

The DataReceivedEventArgs type exposes the following members.

  NameDescription
Public propertyDataGets the line of characters that was written to a redirected Process output stream.
Top

  NameDescription
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

To asynchronously collect the redirected StandardOutput or StandardError stream output of a process, you must create a method that handles the redirected stream output events. The event-handler method is called when the process writes to the redirected stream. The event delegate calls your event handler with an instance of DataReceivedEventArgs. The Data property contains the text line that the process wrote to the redirected stream.

The following code example illustrates how to perform asynchronous read operations on the redirected StandardOutput stream of the sort command. The sort command is a console application that reads and sorts text input.

The example creates an event delegate for the SortOutputHandler event handler and associates it with the OutputDataReceived event. The event handler receives text lines from the redirected StandardOutput stream, formats the text, and writes the text to the screen.

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

Namespace ProcessAsyncStreamSamples

   Class ProcessAsyncOutputRedirection
      ' Define static variables shared by class methods. 
      Private Shared sortOutput As StringBuilder = Nothing 
      Private Shared numOutputLines As Integer = 0

      Public Shared Sub SortInputListText()

         ' Initialize the process and its StartInfo properties. 
         ' The sort command is a console application that 
         ' reads and sorts text input. 
         Dim sortProcess As New Process()
         sortProcess.StartInfo.FileName = "Sort.exe" 

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

         ' Redirect the standard output of the sort command.   
         ' Read the stream asynchronously using an event handler.
         sortProcess.StartInfo.RedirectStandardOutput = True
         sortOutput = new StringBuilder()

         ' Set our event handler to asynchronously read the sort output. 
         AddHandler sortProcess.OutputDataReceived, _
                    AddressOf SortOutputHandler

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

         ' Start the process.
         sortProcess.Start()

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

         ' Start the asynchronous read of the sort output stream.
         sortProcess.BeginOutputReadLine()

         ' 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.
         sortProcess.WaitForExit()

         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(sortOutput)
         Else
            Console.WriteLine(" No input lines were sorted.")
         End If

         sortProcess.Close()
      End Sub  

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

         ' Collect the sort command output. 
         If Not String.IsNullOrEmpty(outLine.Data) Then
            numOutputLines += 1

            ' Add the text to the collected output.
            sortOutput.Append(Environment.NewLine + "[" _
                         + numOutputLines.ToString() + "] - " _
                         + outLine.Data)
         End If 
      End Sub  
   End Class   
End Namespace  

Namespace ProcessAsyncStreamSamples

   Class ProcessSampleMain

      ' The main entry point for the application. 
      Shared Sub Main()
         Try
            ProcessAsyncOutputRedirection.SortInputListText()

         Catch e As InvalidOperationException
            Console.WriteLine("Exception:")
            Console.WriteLine(e.ToString())
         End Try 
      End Sub 'Main
   End Class  'ProcessSampleMain
End Namespace 'Process_AsyncStream_Sample

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft