.NET Framework 提供豐富的網路類別庫,位於 System.Net 命名空間。本文透過建立檔案下載器,示範高層網路程式設計核心概念與實作流程。
| 層次 | 類別 | 功能 |
|---|---|---|
| 請求/回應層 | WebRequest, WebResponse | 統一資源存取抽象基底 |
| 應用協定層 | HttpWebRequest, FtpWebRequest | 特定協定實作 |
| 高層封裝 | WebClient | 簡化常見操作 (下載/上傳) |
try {
WebRequest myre = WebRequest.Create(URLAddress);
} catch (WebException exp) {
MessageBox.Show(exp.Message, "Error");
}
statusBar.Text = "開始下載檔案...";
client.DownloadFile(URLAddress, fileName);
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[100000];
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;
statusBar.Text = "正在接收資料...";
while (allmybyte > 0) {
int m = str.Read(mbyte, startmbyte, allmybyte);
if (m == 0) break;
startmbyte += m;
allmybyte -= m;
}
FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, startmbyte);
str.Close();
fstr.Close();
statusBar.Text = "下載完畢!";
private void Start_Click(object sender, System.EventArgs e) {
Thread th = new Thread(new ThreadStart(StartDownload));
th.Start();
}
using System.Net; // WebRequest, WebClient
using System.IO; // Stream, FileStream, StreamReader
using System.Threading; // Thread, ThreadStart
WebException:網路下載錯誤UriFormatException:URI 格式無效IOException:檔案存取錯誤SecurityException:權限不足UploadFile / UploadData:檔案上傳DownloadData:下載為位元組陣列DownloadString:直接下載字串DownloadFileAsync:非同步下載 (事件通知進度)下篇將提供完整可編譯原始碼與架構深度分析。