引用命名空间:

using System.Net;//网络功能 
using System.IO;//流支持
using System.Threading;//线程支持

 定义线程下载主体:

 1  public class threadbody
 2     {        
 3         Program p;
 4         int i;
 5         public threadbody( Program t_p,int t_i)
 6         {
 7             p = t_p;
 8             i = t_i;
 9         }
10 
11         public void Download()
12         {
13             try
14             {
15                 string filename = p.filenamew[i];
16                 FileStream fsteam=new FileStream(filename, System.IO.FileMode.Create);
17                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(p.StrUrl);
18                 request.AddRange(p.filestartw[i], p.filestartw[i] + p.filesizew[i]);//设置Range值
19                 //向服务器请求,获得服务器回应数据流
20                 System.IO.Stream ns = request.GetResponse().GetResponseStream();
21                 byte[] nbytes = new byte[1024];
22                 int nReadSize = 0;
23                 nReadSize = ns.Read(nbytes, 0, 1024);
24                 while (nReadSize > 0)
25                 {
26                     fsteam.Write(nbytes, 0, nReadSize);
27                     nReadSize = ns.Read(nbytes, 0, 1024);
28                 }
29 
30                 fsteam.Close();
31                 ns.Close();
32                Console.WriteLine("线程{0}下载完成", i);
33                p.threadw[i] = true;//表明此线程结束。
34             }
35 
36             catch (Exception ex)
37             {
38 
39                 //p.fs.Close();
40 
41                 Console.WriteLine("下载过程中出现错误:" + ex.ToString());
42 
43             }            
44 
45         }
46     }
View Code

相关文章: