英語で読む

次の方法で共有


Process.OutputDataReceived イベント

定義

アプリケーションが、リダイレクトされた StandardOutput ストリームに行を書き込む度に発生します。

public event System.Diagnostics.DataReceivedEventHandler? OutputDataReceived;
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived;
[System.ComponentModel.Browsable(true)]
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived;

イベントの種類

属性

次の例は、 コマンドのリダイレクトされた StandardOutput ストリームに対して非同期読み取り操作を実行する方法を ipconfig 示しています。

この例では、イベント ハンドラーのイベント デリゲートを OutputHandler 作成し、イベントに OutputDataReceived 関連付けます。 イベント ハンドラーは、リダイレクトされた StandardOutput ストリームからテキスト行を受け取り、テキストの書式を設定し、後で例のコンソール ウィンドウに示す出力文字列に保存します。

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();
    }
}

注釈

イベントは OutputDataReceived 、関連付けられている Process が改行 (復帰 (CR)、改行 (LF)、または CR + LF) で終了した行を、リダイレクトされたストリームに書き込んだ StandardOutput ことを示します。

イベントは、 の非同期読み取り操作中に StandardOutput有効になります。 非同期読み取り操作を開始するには、 のストリームをStandardOutputリダイレクトし、イベント ハンドラーを イベントにOutputDataReceived追加し、 を呼び出すBeginOutputReadLine必要Processがあります。 その後、イベントはOutputDataReceived、プロセスが終了するか を呼び出CancelOutputReadすまで、プロセスがリダイレクトされたStandardOutputストリームに行を書き込むたびに通知します。

注意

非同期出力を処理しているアプリケーションは、 メソッドを WaitForExit 呼び出して、出力バッファーがフラッシュされていることを確認する必要があります。

適用対象

こちらもご覧ください