WebClient.DownloadStringCompleted 事件

定義

發生於異步資源下載作業完成時。

C#
public event System.Net.DownloadStringCompletedEventHandler? DownloadStringCompleted;
C#
public event System.Net.DownloadStringCompletedEventHandler DownloadStringCompleted;

事件類型

範例

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

C#
// Sample call : DownloadStringInBackground2 ("http://www.contoso.com/GameScores.html");
public static void DownloadStringInBackground2(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    // Specify that the DownloadStringCallback2 method gets called
    // when the download completes.
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);
    client.DownloadStringAsync(uri);
}

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

C#
private static void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
    // If the request was not canceled and did not throw
    // an exception, display the resource.
    if (!e.Cancelled && e.Error == null)
    {
        string textString = (string)e.Result;

        Console.WriteLine(textString);
    }
}

備註

注意

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

每次異步操作以字串完成下載資源時,都會引發此事件。 這些作業會藉由呼叫 DownloadStringAsync 方法啟動。

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

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

適用於

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