Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Process Class
Process Methods
 BeginOutputReadLine Method

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Process..::.BeginOutputReadLine Method

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

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)
Visual Basic (Declaration)
<ComVisibleAttribute(False)> _
Public Sub BeginOutputReadLine
Visual Basic (Usage)
Dim instance As Process

instance.BeginOutputReadLine()
C#
[ComVisibleAttribute(false)]
public void BeginOutputReadLine()
Visual C++
[ComVisibleAttribute(false)]
public:
void BeginOutputReadLine()
JScript
public function BeginOutputReadLine()
ExceptionCondition
InvalidOperationException

The ProcessStartInfo..::.RedirectStandardOutput property is false.

- or -

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

- or -

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

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

In contrast, BeginOutputReadLine starts asynchronous read operations on the StandardOutput stream. This method enables a 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 StandardOutput for a Process :

  1. Set UseShellExecute to false.

  2. Set RedirectStandardOutput to true.

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

  4. Start the Process.

  5. Call BeginOutputReadLine for the Process. This call starts asynchronous read operations on StandardOutput.

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

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

NoteNote:

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 BeginOutputReadLine with a call to ReadLine on the StandardOutput stream, or vice versa. However, you can read two different streams in different modes. For example, you can call BeginOutputReadLine and then call ReadLine for the StandardError stream.

The following 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.

Visual Basic
' 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 

C#
// Define the namespaces used by this sample.
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace ProcessAsyncStreamSamples
{
    class SortOutputRedirection
    {
        // Define static variables shared by class methods.
        private static StringBuilder sortOutput = null;
        private static int numOutputLines = 0;

        public static void SortInputListText()
        {
            // Initialize the process and its StartInfo properties.
            // The sort command is a console application that
            // reads and sorts text input.

            Process sortProcess;
            sortProcess = 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.  
            // This stream is read asynchronously using an event handler.
            sortProcess.StartInfo.RedirectStandardOutput = true;
            sortOutput = new StringBuilder("");

            // Set our event handler to asynchronously read the sort output.
            sortProcess.OutputDataReceived += new DataReceivedEventHandler(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.
            StreamWriter sortStreamWriter = 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");

            String inputText;
            int numInputLines = 0;
            do 
            {
                Console.WriteLine("Enter a text line (or press the Enter key to stop):");

                inputText = Console.ReadLine();
                if (!String.IsNullOrEmpty(inputText))
                {
                    numInputLines ++;
                    sortStreamWriter.WriteLine(inputText);
                }
            }
            while (!String.IsNullOrEmpty(inputText) && (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 (numOutputLines > 0)
            {
                // 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.");
            }

            sortProcess.Close();
        }

        private static void SortOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
            // Collect the sort command output.
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                numOutputLines++;

                // Add the text to the collected output.
                sortOutput.Append(Environment.NewLine + 
                    "[" + numOutputLines.ToString() + "] - " + outLine.Data);
            }
        }
    }
}

Visual C++
// Define the namespaces used by this sample.
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace System::ComponentModel;

ref class SortOutputRedirection
{
private:
   // Define static variables shared by class methods.
   static StringBuilder^ sortOutput = nullptr;
   static int numOutputLines = 0;

public:
   static void SortInputListText()
   {
      // Initialize the process and its StartInfo properties.
      // The sort command is a console application that
      // reads and sorts text input.

      Process^ sortProcess;
      sortProcess = gcnew Process;
      sortProcess->StartInfo->FileName = "Sort.exe";

      // Set UseShellExecute to false for redirection.
      sortProcess->StartInfo->UseShellExecute = false;

      // Redirect the standard output of the sort command.  
      // This stream is read asynchronously using an event handler.
      sortProcess->StartInfo->RedirectStandardOutput = true;
      sortOutput = gcnew StringBuilder;

      // Set our event handler to asynchronously read the sort output.
      sortProcess->OutputDataReceived += gcnew DataReceivedEventHandler( 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.
      StreamWriter^ sortStreamWriter = 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" );

      String^ inputText;
      int numInputLines = 0;
      do
      {
         Console::WriteLine( "Enter a text line (or press the Enter key to stop):" );

         inputText = Console::ReadLine();
         if (  !String::IsNullOrEmpty( inputText ) )
         {
            numInputLines++;
            sortStreamWriter->WriteLine( inputText );
         }
      }
      while (  !String::IsNullOrEmpty( inputText ) && (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 ( numOutputLines > 0 )
      {

         // Write the formatted and sorted output to the console.
         Console::WriteLine( " Sort results = {0} sorted text line(s) ",
            numOutputLines.ToString() );
         Console::WriteLine( "----------" );
         Console::WriteLine( sortOutput->ToString() );
      }
      else
      {
         Console::WriteLine( " No input lines were sorted." );
      }

      sortProcess->Close();
   }

private:
   static void SortOutputHandler( Object^ /*sendingProcess*/,
      DataReceivedEventArgs^ outLine )
   {
      // Collect the sort command output.
      if (  !String::IsNullOrEmpty( outLine->Data ) )
      {
         numOutputLines++;

         // Add the text to the collected output.
         sortOutput->AppendFormat( "\n[{0}] {1}",
            numOutputLines.ToString(), outLine->Data );
      }
   }
};

  • LinkDemand 

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker