萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# WebClient 完整實戰指南:下載、上傳、串流與常見坑點

WebClient 定位

WebClient 是 .NET Framework 早期提供的高階 HTTP 客戶端,封裝 HttpWebRequest,支援 HTTP/HTTPS/File 協定,**適合簡單同步操作**。現代專案建議改用 HttpClient (非同步、可重用、效能更佳)。

核心功能與程式碼範例

1. 下載檔案到磁碟 — DownloadFile

using (var wc = new WebClient())
{
    wc.DownloadFile("https://example.com/file.zip", @"C:\Downloads\file.zip");
}

2. 以串流方式讀取回應內容 — OpenRead

using (var wc = new WebClient())
using (var stream = wc.OpenRead("https://api.example.com/data.json"))
using (var reader = new StreamReader(stream))
{
    string json = reader.ReadToEnd();
    // 反序列化...
}

3. 以串流方式上傳資料 — OpenWrite

using (var wc = new WebClient())
using (var stream = wc.OpenWrite("https://api.example.com/upload", "PUT"))
using (var writer = new StreamWriter(stream))
{
    writer.WriteLine("Hello World");
    writer.Flush(); // 確保送出
}

4. 上傳本機檔案 — UploadFile

using (var wc = new WebClient())
{
    byte[] response = wc.UploadFile("https://api.example.com/upload", "POST", @"C:\Data\report.pdf");
    // response 為伺服器回應位元組陣列
}

5. 上傳位元組陣列 — UploadData

byte[] fileBytes = File.ReadAllBytes(@"C:\Image\photo.jpg");
using (var wc = new WebClient())
{
    wc.UploadData("https://api.example.com/upload", "PUT", fileBytes);
}

常見問題與解決方案

❌ 問題 1:無法處理驗證/憑證

WebClient 不支援客戶端憑證、OAuth Bearer Token 等進階驗證。
✅ 解法:改用 HttpClient + HttpClientHandler.ClientCertificates 或設定 DefaultRequestHeaders.Authorization。

❌ 問題 2:大檔案記憶體壓力

DownloadData/UploadData 會將整個內容載入記憶體。
✅ 解法:使用 OpenRead/OpenWrite 串流處理,或改用 HttpClient 搭配 HttpCompletionOption.ResponseHeadersRead。

❌ 問題 3:同步阻塞 UI/執行緒

所有方法皆為同步阻塞。
✅ 解法:WebClient 提供 *Async 版本 (如 DownloadFileTaskAsync),但建議直接遷移至 HttpClient 非同步模型。

❌ 問題 4:編碼亂碼

wc.Encoding = Encoding.UTF8; // 強制指定回應編碼,避免預設 ISO-8859-1 導致中文亂碼

遷移建議:WebClient → HttpClient

// 單例模式,全域共用
private static readonly HttpClient _http = new HttpClient();

public async Task GetJsonAsync(string url)
{
    _http.DefaultRequestHeaders.UserAgent.ParseAdd("MyApp/1.0");
    return await _http.GetStringAsync(url);
}

public async Task DownloadBytesAsync(string url)
{
    return await _http.GetByteArrayAsync(url);
}

public async Task UploadFileAsync(string url, string filePath)
{
    using var content = new MultipartFormDataContent();
    using var fileStream = File.OpenRead(filePath);
    content.Add(new StreamContent(fileStream), "file", Path.GetFileName(filePath));
    return await _http.PostAsync(url, content);
}

總結

WebClient 適合快速原型、舊專案維護;新專案請直接採用 HttpClient 獲得完整非同步、連線池、驗證與串流控制能力。

copyright © 萬盛學電腦網 all rights reserved