Process::BeginErrorReadLine Method

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

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

void BeginErrorReadLine()


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.
#using <System.dll>

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

ref class ProcessNetStreamRedirection
   // Define static variables shared by class methods. 
   static StreamWriter^ streamError = nullptr;
   static String^ netErrorFile = "";
   static StringBuilder^ netOutput = nullptr;
   static bool errorRedirect = false;
   static bool errorsWritten = false;

   static void RedirectNetCommandStreams()
      String^ netArguments;
      Process^ netProcess;

      // 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 ) )
         // Default to the help command if there is not an input argument.
         netArguments = "/?";

      // 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 (  !String::IsNullOrEmpty( netErrorFile ) )
         errorRedirect = true;

      // 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 = gcnew Process;
      netProcess->StartInfo->FileName = "Net.exe";

      // Build the net command argument list.
      netProcess->StartInfo->Arguments = String::Format( "view {0}", netArguments );

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

      // Redirect the standard output of the net command.   
      // This stream is read asynchronously using an event handler.
      netProcess->StartInfo->RedirectStandardOutput = true;
      netProcess->OutputDataReceived += gcnew DataReceivedEventHandler( NetOutputDataHandler );
      netOutput = gcnew StringBuilder;
      if ( errorRedirect )

         // Redirect the error output of the net command. 
         netProcess->StartInfo->RedirectStandardError = true;
         netProcess->ErrorDataReceived += gcnew DataReceivedEventHandler( NetErrorDataHandler );

         // Do not redirect the error output.
         netProcess->StartInfo->RedirectStandardError = false;

      Console::WriteLine( "\nStarting process: net {0}",
         netProcess->StartInfo->Arguments );
      if ( errorRedirect )
         Console::WriteLine( "Errors will be written to the file {0}", netErrorFile );

      // Start the process.

      // Start the asynchronous read of the standard output stream.

      if ( errorRedirect )
         // Start the asynchronous read of the standard 
         // error stream.

      // Let the net command run, collecting the output.

      if ( streamError != nullptr )
         // 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;

      if ( netOutput->Length > 0 )
         // If the process wrote more than just 
         // white space, write the output to the console.
         Console::WriteLine( "\nPublic network shares from net view:\n{0}\n",
            netOutput->ToString() );

      if ( errorsWritten )
         // Signal that the error file had something  
         // written to it. 
         array<String^>^errorOutput = File::ReadAllLines( netErrorFile );
         if ( errorOutput->Length > 0 )
            Console::WriteLine( "\nThe following error output was appended to {0}.",
               netErrorFile );
            System::Collections::IEnumerator^ myEnum = errorOutput->GetEnumerator();
            while ( myEnum->MoveNext() )
               String^ errLine = safe_cast<String^>(myEnum->Current);
               Console::WriteLine( "  {0}", errLine );



   static void NetOutputDataHandler( Object^ /*sendingProcess*/,
      DataReceivedEventArgs^ outLine )
      // Collect the net view command output. 
      if (  !String::IsNullOrEmpty( outLine->Data ) )
         // Add the text to the collected output.
         netOutput->AppendFormat(  "\n  {0}", outLine->Data );

   static void NetErrorDataHandler( Object^ /*sendingProcess*/,
      DataReceivedEventArgs^ errLine )
      // Write the error text to the file if there is something to  
      // write and an error file has been specified. 

      if (  !String::IsNullOrEmpty( errLine->Data ) )
         if (  !errorsWritten )
            if ( streamError == nullptr )
               // Open the file. 
                  streamError = gcnew StreamWriter( netErrorFile,true );
               catch ( Exception^ e ) 
                  Console::WriteLine(  "Could not open error file!" );
                  Console::WriteLine( e->Message->ToString() );

            if ( streamError != nullptr )
               // Write a header to the file if this is the first 
               // call to the error output handler.
               streamError->WriteLine( DateTime::Now.ToString() );
               streamError->WriteLine(  "Net View error output:" );
            errorsWritten = true;

         if ( streamError != nullptr )
            // Write redirected errors to the file.
            streamError->WriteLine( errLine->Data );

.NET Framework

Supported in: 4.6, 4.5, 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.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft