英語で読む

次の方法で共有


DataReceivedEventArgs.Data プロパティ

定義

リダイレクトされた Process 出力ストリームに書き込まれた文字の行を取得します。

C#
public string? Data { get; }
C#
public string Data { get; }

プロパティ値

関連する Process によって、リダイレクトされた StandardOutput または StandardError ストリームに書き込まれた行。

次のコード例は、 イベントに関連付けられた単純なイベント ハンドラーを OutputDataReceived 示しています。 イベント ハンドラーは、リダイレクトされた StandardOutput ストリームからテキスト行を受け取り、テキストの書式設定を行い、テキストを画面に書き込みます。

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

注釈

または StandardErrorProcessストリームをイベント ハンドラーにリダイレクトStandardOutputすると、プロセスがリダイレクトされたストリームに行を書き込むたびにイベントが発生します。 プロパティは Data 、 が Process リダイレクトされた出力ストリームに書き込んだ行です。 イベント ハンドラーでは、 プロパティを Data 使用してプロセス出力をフィルター処理したり、別の場所に出力を書き込んだりできます。 たとえば、すべてのエラー出力行を指定されたエラー ログ ファイルに格納するイベント ハンドラーを作成できます。

行は、一連の文字の後に改行 ("\n") または復帰した直後に改行 ("\r\n") として定義されます。 行文字は、既定のシステム ANSI コード ページを使用してエンコードされます。 プロパティには Data 、終端復帰または改行は含まれません。

リダイレクトされたストリームが閉じられると、null 行がイベント ハンドラーに送信されます。 イベント ハンドラーがプロパティにアクセスする前に、プロパティを Data 適切にチェックしていることを確認します。 たとえば、静的メソッド String.IsNullOrEmpty を使用して、イベント ハンドラーの プロパティを Data 検証できます。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1