本文示範如何使用 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 與實際讀取位元組數。BackgroundWorker 或 async/await。
延伸閱讀: C# 非同步下載、大檔案分塊下載、斷點續傳實作。