Process.OutputDataReceived Process.OutputDataReceived Process.OutputDataReceived Process.OutputDataReceived Event

Definizione

Si verifica quando un'applicazione scrive nel proprio flusso StandardOutput reindirizzato.Occurs each time an application writes a line to its redirected StandardOutput stream.

public:
 event System::Diagnostics::DataReceivedEventHandler ^ OutputDataReceived;
[System.ComponentModel.Browsable(true)]
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived;
member this.OutputDataReceived : System.Diagnostics.DataReceivedEventHandler 
Public Custom Event OutputDataReceived As DataReceivedEventHandler 
Attributi

Esempi

L'esempio seguente illustra come eseguire operazioni di lettura asincrona sul reindirizzato StandardOutput flusso dei ipconfig comando.The following example illustrates how to perform asynchronous read operations on the redirected StandardOutput stream of the ipconfig command.

Nell'esempio viene creato un delegato per il OutputHandler gestore dell'evento e la associa il OutputDataReceived evento.The example creates an event delegate for the OutputHandler event handler and associates it with the OutputDataReceived event. Il gestore eventi riceve le righe di testo da reindirizzato StandardOutput flusso, formatta il testo e salvarlo in una stringa di output che viene visualizzata in un secondo momento nella finestra della console di esempio.The event handler receives text lines from the redirected StandardOutput stream, formats the text, and saves it in an output string that's later shown in the example's console window.

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

ref class StandardAsyncOutputExample
{
private:
    static int lineCount = 0;
    static StringBuilder^ output = nullptr;

public:
    static void Run()
    {
        Process^ process = gcnew Process();
        process->StartInfo->FileName = "ipconfig.exe";
        process->StartInfo->UseShellExecute = false;
        process->StartInfo->RedirectStandardOutput = true;
        output = gcnew StringBuilder();
        process->OutputDataReceived += gcnew DataReceivedEventHandler(OutputHandler);
        process->Start();

        // Asynchronously read the standard output of the spawned process. 
        // This raises OutputDataReceived events for each line of output.
        process->BeginOutputReadLine();
        process->WaitForExit();

        // Write the redirected output to this application's window.
        Console::WriteLine(output);

        process->WaitForExit();
        process->Close();

        Console::WriteLine("\n\nPress any key to exit");
        Console::ReadLine();
    }

private:
    static void OutputHandler(Object^ sender, DataReceivedEventArgs^ e)
    {
        // Prepend line numbers to each line of the output.
        if (!String::IsNullOrEmpty(e->Data))
        {
            lineCount++;
            output->Append("\n[" + lineCount + "]: " + e->Data);
        }
    }
};

int main()
{
    StandardAsyncOutputExample::Run();
}
using System;
using System.IO;
using System.Diagnostics;
using System.Text;

class StandardAsyncOutputExample
{
    private static int lineCount = 0;
    private static StringBuilder output = new StringBuilder();

    public static void Main()
    {
        Process process = new Process();
        process.StartInfo.FileName = "ipconfig.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
        {
            // Prepend line numbers to each line of the output.
            if (!String.IsNullOrEmpty(e.Data))
            {
                lineCount++;
                output.Append("\n[" + lineCount + "]: " + e.Data);
            }
        });

        process.Start();

        // Asynchronously read the standard output of the spawned process. 
        // This raises OutputDataReceived events for each line of output.
        process.BeginOutputReadLine();
        process.WaitForExit();

        // Write the redirected output to this application's window.
        Console.WriteLine(output);

        process.WaitForExit();
        process.Close();

        Console.WriteLine("\n\nPress any key to exit.");
        Console.ReadLine();
    }
}
Imports System
Imports System.IO
Imports System.Diagnostics
Imports System.Text

Module Module1
    Dim lineCount As Integer = 0
    Dim output As StringBuilder = New StringBuilder()

    Sub Main()
        Dim process As New Process()
        process.StartInfo.FileName = "ipconfig.exe"
        process.StartInfo.UseShellExecute = False
        process.StartInfo.RedirectStandardOutput = True
        AddHandler process.OutputDataReceived, AddressOf OutputHandler
        process.Start()

        ' Asynchronously read the standard output of the spawned process. 
        ' This raises OutputDataReceived events for each line of output.
        process.BeginOutputReadLine()
        process.WaitForExit()

        Console.WriteLine(output)

        process.WaitForExit()
        process.Close()

        Console.WriteLine(Environment.NewLine + Environment.NewLine + "Press any key to exit.")
        Console.ReadLine()
    End Sub

    Sub OutputHandler(sender As Object, e As DataReceivedEventArgs)
        If Not String.IsNullOrEmpty(e.Data) Then
            lineCount += 1

            ' Add the text to the collected output.
            output.Append(Environment.NewLine + "[" + lineCount.ToString() + "]: " + e.Data)
        End If
    End Sub
End Module

Commenti

Il OutputDataReceived evento indica che l'oggetto associato Process ha scritto una riga, terminare con un carattere di nuova riga, nel proprio flusso StandardOutput flusso.The OutputDataReceived event indicates that the associated Process has written a line, terminating with a newline character, to its redirected StandardOutput stream.

L'evento è abilitato durante operazioni di lettura asincrona sul StandardOutput.The event is enabled during asynchronous read operations on StandardOutput. Per avviare operazioni di lettura asincrona, è necessario reindirizzare il StandardOutput flusso di un Process, aggiungere il gestore eventi per il OutputDataReceived evento, quindi chiamare BeginOutputReadLine.To start asynchronous read operations, you must redirect the StandardOutput stream of a Process, add your event handler to the OutputDataReceived event, and call BeginOutputReadLine. Successivamente, il OutputDataReceived segnali di evento ogni volta che il processo scrive una riga in reindirizzato StandardOutput streaming, fino a quando il processo viene chiuso o chiama CancelOutputRead.Thereafter, the OutputDataReceived event signals each time the process writes a line to the redirected StandardOutput stream, until the process exits or calls CancelOutputRead.

Nota

L'applicazione di elaborazione dell'output asincrono deve chiamare il WaitForExit metodo per assicurarsi che il buffer di output è stato scaricato.The application that is processing the asynchronous output should call the WaitForExit method to ensure that the output buffer has been flushed.

Sicurezza

LinkDemand
per un'attendibilità totale per il chiamante immediato.for full trust for the immediate caller. Impossibile utilizzare questo membro in codice parzialmente attendibile.This member cannot be used by partially trusted code.

Si applica a

Vedi anche