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

Nell'esempio seguente viene illustrato come eseguire operazioni di lettura asincrona sul flusso reindirizzato StandardOutput ipconfig del 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 dell'evento OutputHandler per il gestore eventi che viene associato OutputDataReceived all'evento.The example creates an event delegate for the OutputHandler event handler and associates it with the OutputDataReceived event. Il gestore eventi riceve righe di testo dal flusso StandardOutput reindirizzato, formatta il testo e lo salva in una stringa di output che verrà visualizzata in un secondo momento nella finestra della console dell'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

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

L'evento viene abilitato durante le operazioni di lettura StandardOutputasincrona su.The event is enabled during asynchronous read operations on StandardOutput. Per avviare le operazioni di lettura asincrone, è necessario StandardOutput reindirizzare Processil flusso di un oggetto, aggiungere OutputDataReceived il gestore eventi all' BeginOutputReadLineevento e chiamare.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, l' OutputDataReceived evento segnala ogni volta che il processo scrive una riga nel flusso StandardOutput reindirizzato, fino a quando il processo CancelOutputReadnon viene chiuso o chiama.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 che elabora l'output asincrono deve chiamare il WaitForExit metodo per assicurarsi che il buffer di output sia 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 l'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