Process.OutputDataReceived 事件

定義

發生於應用程式將某行寫入至其重新導向的 StandardOutput 資料流時。

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

事件類型

屬性

範例

下列範例說明如何在命令的ipconfig重新導向StandardOutput數據流上執行異步讀取作業。

此範例會建立 OutputHandler 事件處理程式的事件委派,並將它與 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();
    }
}

備註

事件 OutputDataReceived 指出相關聯的 Process 已寫入換行字元 (換行字元 (換行字元, (CR) 、換行字元 (LF) ,或 CR+LF) 重新導向 StandardOutput 數據流。

事件會在上的 StandardOutput異步讀取作業期間啟用。 若要啟動異步讀取作業,您必須將 的Process資料流重新導向StandardOutput、將事件處理程式新增至 OutputDataReceived 事件,然後呼叫 BeginOutputReadLine。 之後, OutputDataReceived 每當進程將一行寫入重新導向 StandardOutput 數據流時,事件就會發出訊號,直到進程結束或呼叫 CancelOutputRead為止。

備註

正在處理異步輸出的應用程式應該呼叫 WaitForExit 方法,以確保已清除輸出緩衝區。

適用於

產品 版本
.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

另請參閱