首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# WebClient 實現伺服器檔案下載至客戶端

     編輯:程式設計疑難解答

適用場景

**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。
  • SSL/TLS 憑證驗證:生產環境請保持預設驗證;測試環境若需忽略錯誤,可設定 ServicePointManager.ServerCertificateValidationCallback (僅限測試)。

常見錯誤排查

錯誤原因解決
403 Forbidden伺服器拒絕存取 (Referer/User-Agent/Token 校驗)補全請求 Header,模擬瀏覽器行為
404 Not FoundURL 錯誤或檔案不存在瀏覽器驗證 URL 可直接下載
WebException: Timeout網路慢或伺服器無回應調大 client.Timeout (毫秒)
UnauthorizedAccessException目標目錄無寫入權限以管理員執行 / 選擇有權限目錄
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved