WebClient.OpenWriteCompleted 事件

定義

當異步操作開啟數據流以將數據寫入資源完成時發生。

C#
public event System.Net.OpenWriteCompletedEventHandler? OpenWriteCompleted;
C#
public event System.Net.OpenWriteCompletedEventHandler OpenWriteCompleted;

事件類型

範例

下列程式代碼範例示範如何設定此事件的事件處理程式。

C#
public static void OpenResourceForWriting2(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    // Specify that the OpenWriteCallback method gets called
    // when the writeable stream is available.
    client.OpenWriteCompleted += new OpenWriteCompletedEventHandler(OpenWriteCallback2);
    client.OpenWriteAsync(uri, "POST");
    // Applications can perform other tasks
    // while waiting for the upload to complete.
}

下列程式代碼範例示範此事件的處理程序實作。

C#
private static void OpenWriteCallback2(Object sender, OpenWriteCompletedEventArgs e)
{
    Stream body = null;
    StreamWriter s = null;

    try
    {
        body = (Stream)e.Result;
        s = new StreamWriter(body);
        s.AutoFlush = true;
        s.Write("This is content data to be sent to the server.");
    }
    finally
    {
        if (s != null)
        {
            s.Close();
        }

        if (body != null)
        {
            body.Close();
        }
    }
}

備註

警告

WebRequestHttpWebRequestServicePointWebClient 已經過時,您不應該將它們用於新的開發。 請改用 HttpClient

每次異步操作開啟用來將數據傳送至資源完成的數據流時,都會引發此事件。 這些作業會藉由呼叫 OpenWriteAsync 方法啟動。

OpenWriteCompletedEventHandler 是這個事件的委派。 OpenWriteCompletedEventArgs 類別會提供事件處理程式與事件數據。

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.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