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.
Traducción
Inglés

Método Process.BeginErrorReadLine ()

 

Publicado: noviembre de 2016

Inicia las operaciones de lectura asincrónica en la secuencia de StandardError redirigida de la aplicación.

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

[ComVisibleAttribute(false)]
public void BeginErrorReadLine()

Exception Condition
InvalidOperationException

La propiedad ProcessStartInfo.RedirectStandardError es false.

o bien

Ya hay una operación de lectura asincrónica en curso en la secuencia StandardError.

o bien

Una operación de lectura sincrónica ha utilizado la secuencia StandardError.

The P:System.Diagnostics.Process.StandardError stream can be read synchronously or asynchronously. Methods such as M:System.IO.StreamReader.Read, M:System.IO.StreamReader.ReadLine, and M:System.IO.StreamReader.ReadToEnd perform synchronous read operations on the error output stream of the process. These synchronous read operations do not complete until the associated T:System.Diagnostics.Process writes to its P:System.Diagnostics.Process.StandardError stream, or closes the stream.

In contrast, M:System.Diagnostics.Process.BeginErrorReadLine starts asynchronous read operations on the P:System.Diagnostics.Process.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 P:System.Diagnostics.Process.StandardError for a T:System.Diagnostics.Process :

  1. Set P:System.Diagnostics.ProcessStartInfo.UseShellExecute to false.

  2. Set P:System.Diagnostics.ProcessStartInfo.RedirectStandardError to true.

  3. Add your event handler to the E:System.Diagnostics.Process.ErrorDataReceived event. The event handler must match the T:System.Diagnostics.DataReceivedEventHandler delegate signature.

  4. Start the T:System.Diagnostics.Process.

  5. Call M:System.Diagnostics.Process.BeginErrorReadLine for the T:System.Diagnostics.Process. This call starts asynchronous read operations on P:System.Diagnostics.Process.StandardError.

When asynchronous read operations start, the event handler is called each time the associated T:System.Diagnostics.Process writes a line of text to its P:System.Diagnostics.Process.StandardError stream.

You can cancel an asynchronous read operation by calling M:System.Diagnostics.Process.CancelErrorRead. The read operation can be canceled by the caller or by the event handler. After canceling, you can call M:System.Diagnostics.Process.BeginErrorReadLine again to resume asynchronous read operations.

System_CAPS_noteNota

You cannot mix asynchronous and synchronous read operations on a redirected stream. Once the redirected stream of a T:System.Diagnostics.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 M:System.Diagnostics.Process.BeginErrorReadLine with a call to M:System.IO.StreamReader.ReadLine on the P:System.Diagnostics.Process.StandardError stream, or vice versa. However, you can read two different streams in different modes. For example, you can call M:System.Diagnostics.Process.BeginErrorReadLine and then call M:System.IO.StreamReader.ReadLine for the P:System.Diagnostics.Process.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;
using System.Text;
using System.Globalization;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;


namespace ProcessAsyncStreamSamples
{

    class ProcessNetStreamRedirection
    {
        // Define static variables shared by class methods.
        private static StreamWriter streamError =null;
        private static String netErrorFile = "";
        private static StringBuilder netOutput = null;
        private static bool errorRedirect = false;
        private static bool errorsWritten = false;

        public 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 = new 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 += new DataReceivedEventHandler(NetOutputDataHandler);
            netOutput = new StringBuilder();

            if (errorRedirect)
            {
                // Redirect the error output of the net command. 
                netProcess.StartInfo.RedirectStandardError = true;
                netProcess.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
            }
            else 
            {
                // 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.
            netProcess.Start();

            // Start the asynchronous read of the standard output stream.
            netProcess.BeginOutputReadLine();

            if (errorRedirect)
            {
                // Start the asynchronous read of the standard
                // error stream.
                netProcess.BeginErrorReadLine();
            }

            // Let the net command run, collecting the output.
            netProcess.WaitForExit();

            if (streamError != null)
            {
                // Close the error file.
                streamError.Close();
            }
            else 
            {
                // 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);
            }

            if (errorsWritten)
            {
                // Signal that the error file had something 
                // written to it.
                String [] errorOutput = File.ReadAllLines(netErrorFile);
                if (errorOutput.Length > 0)
                {
                    Console.WriteLine("\nThe following error output was appended to {0}.",
                        netErrorFile);
                    foreach (String errLine in errorOutput)
                    {
                        Console.WriteLine("  {0}", errLine);
                    }
                }
                Console.WriteLine();
            }

            netProcess.Close();

        }

        private 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.Append(Environment.NewLine + "  " + outLine.Data);
            }
        }

        private 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 == null)
                    {
                        // Open the file.
                        try 
                        {
                            streamError = new StreamWriter(netErrorFile, true);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not open error file!");
                            Console.WriteLine(e.Message.ToString());
                        }
                    }

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

                if (streamError != null)
                {
                    // Write redirected errors to the file.
                    streamError.WriteLine(errLine.Data);
                    streamError.Flush();
                }
            }
        }
    }
} 

LinkDemand

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
Mostrar: