首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 斷點續傳實作(二):HttpWebRequest Range 標頭與 FileStream Seek 完整程式碼

     編輯:關於C語言

完整實作程式碼

static void Main(string[] args)
{
    string filePath = @"c:\aa.zip";
    string url = "https://www.xxxx.cn/xxxxx.zip";

    long startPos = 0;
    FileStream fs;

    // 1. 開啟或建立本地檔案
    if (File.Exists(filePath))
    {
        fs = File.OpenWrite(filePath);
        startPos = fs.Length;
        fs.Seek(startPos, SeekOrigin.Current);  // 移至檔案尾端
    }
    else
    {
        fs = new FileStream(filePath, FileMode.Create);
        startPos = 0;
    }

    try
    {
        // 2. 建立 HTTP 請求
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        if (startPos > 0)
            request.AddRange((int)startPos);  // 關鍵:設定 Range 標頭

        // 3. 取得回應串流
        using (Stream ns = request.GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[512];
            int readSize;
            
            while ((readSize = ns.Read(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, readSize);
            }
        }

        fs.Close();
        Console.WriteLine("下載完成");
    }
    catch (Exception ex)
    {
        fs.Close();
        Console.WriteLine("下載錯誤: " + ex.ToString());
    }
}

關鍵技術點

HTTP Range 標頭

請求標頭加入 Range: bytes=1024- 表示從第 1024 位元組開始傳輸。HttpWebRequest.AddRange 方法封裝此功能。

FileStream 隨機存取

  • Seek(offset, SeekOrigin.Current):移動讀寫指標至檔案末尾
  • OpenWrite:開啟既有檔案進行附加寫入

適用場景與限制

  • ✅ 靜態檔案下載、支援 Range 的 HTTP 伺服器
  • ✅ 網路中斷後續傳
  • ❌ 動態生成內容 (無 Content-Length)
  • ❌ 不支援 Range 的伺服器 (會重傳整個檔案)
  • ⚠️ 大檔案建議加入進度回報、校驗碼驗證、多執行緒分段下載
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved