WebClient.UploadProgressChanged 事件

定義

發生於異步上傳作業成功傳輸部分或所有數據時。

C#
public event System.Net.UploadProgressChangedEventHandler? UploadProgressChanged;
C#
public event System.Net.UploadProgressChangedEventHandler UploadProgressChanged;

事件類型

範例

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

C#
// Sample call: UploadFileInBackground2("http://www.contoso.com/fileUpload.aspx", "data.txt")
public static void UploadFileInBackground2(string address, string fileName)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback2);

    // Specify a progress notification handler.
    client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
    client.UploadFileAsync(uri, "POST", fileName);
    Console.WriteLine("File upload started.");
}

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

C#
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    uploaded {1} of {2} bytes. {3} % complete...",
        (string)e.UserState,
        e.BytesSent,
        e.TotalBytesToSend,
        e.ProgressPercentage);
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
        (string)e.UserState,
        e.BytesReceived,
        e.TotalBytesToReceive,
        e.ProgressPercentage);
}

備註

警告

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

每次異步上傳進行時,都會引發此事件。 使用下列任何方法啟動上傳時,就會引發此事件。

方法 描述
UploadDataAsync Byte 陣列傳送至資源,而不會封鎖呼叫線程。
UploadFileAsync 將本機檔案傳送至資源,而不會封鎖呼叫線程。
UploadValuesAsync NameValueCollection 傳送至資源,並傳回包含任何回應的 Byte 陣列,而不會封鎖呼叫線程。

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

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

適用於

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