溫馨提示×

c# webclient能實現斷點續傳嗎

c#
小樊
106
2024-11-18 22:24:24
欄目: 編程語言

是的,C# WebClient 類可以實現斷點續傳。要實現斷點續傳,您需要使用 WebClient.DownloadFileTaskAsync 方法,并在請求中設置 Range 頭。以下是一個簡單的示例:

using System;
using System.Net;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://example.com/largefile.zip";
        string localFilePath = "largefile.zip";
        long startPosition = 1024 * 1024; // 從1MB開始下載

        using (WebClient webClient = new WebClient())
        {
            webClient.Headers.Add("Range", $"bytes={startPosition}-");

            try
            {
                await webClient.DownloadFileTaskAsync(url, localFilePath);
                Console.WriteLine("下載完成!");
            }
            catch (WebException e)
            {
                Console.WriteLine("下載失?。?quot; + e.Message);
            }
        }
    }
}

在這個示例中,我們從文件的第二個MB開始下載,直到文件的末尾。Range 頭的值設置為 bytes={startPosition}-,表示從 startPosition 開始下載,直到文件結束。這樣就可以實現斷點續傳功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女