這里只是說明多線程下載的理論基礎,嘿嘿,並沒有寫多線程下載的代碼,標題黨了,但是我相信,看完這個代碼就應該能夠多線程的方式去下載一個文件了.
多線程下載是需要服務器支持的,這里並沒有判斷服務器不支持的情況.
其原理
在發送 http 請求時標記頭文件,告訴服務器我需要這個文件的 第幾個字節 到 第幾個字節.如果服務器不支持讓你分段取文件,可以想想看服務器會怎么做. 沒錯,他把整個文件給你了.
一定得判斷 服務器不支持 的情況.
public void Worker() { string url = "http://files.cnblogs.com/cnryb/HttpSer.zip"; string path = "a.zip"; using (FileStream fs = new FileStream( path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, 2048, FileOptions.RandomAccess )) { //先下載文件的第100個字節到最后 fs.Seek(100, SeekOrigin.Begin); Down(fs, url, 100); //下載前100個字節 fs.Seek(0, SeekOrigin.Begin); Down(fs, url, 0, 99); } }
public void Down(FileStream fs, string url, int start, int end = -1) { HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest; if (end == -1) hwr.AddRange(start); else hwr.AddRange(start, end); HttpWebResponse resp = hwr.GetResponse() as HttpWebResponse; using (Stream input = resp.GetResponseStream()) { byte[] bs = new byte[2048]; int count; while ((count = input.Read(bs, 0, bs.Length)) != 0) { fs.Write(bs, 0, count); } } }