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

C# 實作檔案下載功能:使用 HttpWebRequest 與進度顯示

     編輯:關於C語言

C# 檔案下載完整範例

本文示範如何使用 HttpWebRequest 類別實作檔案下載,並即時顯示下載進度。範例包含基本的錯誤處理與資源釋放,適合 WinForms 應用程式參考。

核心程式碼

using System;
using System.IO;
using System.Net;
using System.Windows.Forms;

public bool DownloadFile(string url, string localPath)
{
    try
    {
        Uri uri = new Uri(url);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream inputStream = response.GetResponseStream())
        using (FileStream outputStream = new FileStream(localPath, FileMode.Create, FileAccess.Write))
        {
            long totalBytes = response.ContentLength;
            long downloadedBytes = 0;
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                downloadedBytes += bytesRead;

                // 每 1KB 更新一次進度
                if (downloadedBytes % 1024 == 0)
                {
                    decimal progress = Math.Round((decimal)downloadedBytes / totalBytes * 100, 2);
                    // 更新 UI 狀態列(需在主執行緒執行)
                    statusBar1.Text = $"檔案大小: {totalBytes} 位元組 | 已下載: {downloadedBytes} 位元組 | 進度: {progress}%";
                }
            }
        }
        return true;
    }
    catch (Exception ex)
    {
        MessageBox.Show($"下載失敗: {ex.Message}");
        return false;
    }
}

按鈕點擊事件範例

private void btnDownload_Click(object sender, EventArgs e)
{
    string url = txtUrl.Text;
    string path = txtPath.Text;

    if (DownloadFile(url, path))
        MessageBox.Show("下載完成!");
    else
        MessageBox.Show("下載過程中發生錯誤。");
}

重點說明

  • 使用 using 區塊確保串流正確關閉釋放。
  • 進度計算採用 ContentLength 與實際讀取位元組數。
  • UI 更新需注意跨執行緒問題,實際專案建議搭配 BackgroundWorker 或 async/await。

延伸閱讀: C# 非同步下載、大檔案分塊下載、斷點續傳實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved