**WinForms / WPF / Console 等桌面應用程式** 從 HTTP/HTTPS 伺服器下載檔案至本地磁碟。**不適用於網頁前端 (ASP.NET/HTML/JS)**。
using System;
using System.Net;
using System.IO;
public class FileDownloader
{
///
/// 下載檔案至指定目錄
///
/// 檔案完整 URL (含檔名)
/// 本地儲存目錄 (需存在且有寫入權限)
/// 可選:自訂儲存檔名,預設取 URL 最後段
public void DownloadFile(string url, string saveDir, string fileName = null)
{
if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException("URL 不能為空");
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
string saveName = fileName ?? Path.GetFileName(new Uri(url).LocalPath);
string savePath = Path.Combine(saveDir, saveName);
using (WebClient client = new WebClient())
{
// 可選:設定 Header、Proxy、Credentials、進度事件
// client.Headers.Add("User-Agent", "MyApp/1.0");
// client.DownloadProgressChanged += (s, e) => Console.WriteLine($"進度: {e.ProgressPercentage}%");
try
{
client.DownloadFile(url, savePath);
Console.WriteLine($"下載完成: {savePath}");
}
catch (WebException ex)
{
Console.WriteLine($"下載失敗: {ex.Message}");
// 根據 ex.Status 細分處理:Timeout, NameResolutionFailure, ProtocolError (404/403) 等
}
}
}
}
DownloadFileTaskAsync (搭配 async/await) 避免阻塞 UI 執行緒。WebClient 不原生支援,需改用 HttpWebRequest 設定 Range Header 或引用第三方庫 (如 Flurl.Http, RestSharp)。OpenRead 獲取 Stream 手動分塊寫入 FileStream。ServicePointManager.ServerCertificateValidationCallback (僅限測試)。| 錯誤 | 原因 | 解決 |
|---|---|---|
| 403 Forbidden | 伺服器拒絕存取 (Referer/User-Agent/Token 校驗) | 補全請求 Header,模擬瀏覽器行為 |
| 404 Not Found | URL 錯誤或檔案不存在 | 瀏覽器驗證 URL 可直接下載 |
| WebException: Timeout | 網路慢或伺服器無回應 | 調大 client.Timeout (毫秒) |
| UnauthorizedAccessException | 目標目錄無寫入權限 | 以管理員執行 / 選擇有權限目錄 |