//c#使用线程下载文件的控制技巧和缺陷
//系统引用//定义线程公共变量//开始线程下载文件//中止线程下载
//系统引用
using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.net; 
using system.io;
using system.text;
using system.threading;
using system.data;
//定义线程公共变量
  public system.threading.thread thread001;
  public system.threading.thread thread002;
//开始线程下载文件
private void button7_click(object sender, system.eventargs e)
  {
   //开始线程下载文件 
   downloadclass a=new downloadclass(); 
   thread001= new thread(new threadstart(a.downloadfile)); 
   a.strurl=textbox1.text;
   a.strfilename=textbox2.text;   
   thread001.start();
   downloadclass b=new downloadclass(); 
   thread002= new thread(new threadstart(b.downloadfile)); 
   b.strurl=textbox3.text;
   b.strfilename=textbox4.text;   
   thread002.start();
  } 
//中止线程下载
private void button5_click(object sender, system.eventargs e)
  {
   //中止线程下载
   thread001.abort();  
   thread002.abort(); 
   messagebox.show("线程已经中止!","警告!");
   
  }
//定义下载文件类.线程传参数用
  public class downloadclass
  {  
   //打开上次下载的文件或新建文件 
   public string strurl;//文件下载网址
   public string strfilename;//下载文件保存地址 
   public string strerror;//返回结果
   public long lstartpos =0; //返回上次下载字节
   public long lcurrentpos=0;//返回当前下载字节
   public long ldownloadfile;//返回当前下载文件长度
   public void downloadfile()
    {    
    system.io.filestream fs; 
    if (system.io.file.exists(strfilename)) 
    { 
     fs= system.io.file.openwrite(strfilename); 
     lstartpos=fs.length; 
     fs.seek(lstartpos,system.io.seekorigin.current);
     //移动文件流中的当前指针 
    } 
    else 
    { 
     fs = new system.io.filestream(strfilename,system.io.filemode.create); 
     lstartpos =0;
    } 
    //打开网络连接 
    try 
    { 
     system.net.httpwebrequest request =(system.net.httpwebrequest)system.net.httpwebrequest.create(strurl); 
     long length=request.getresponse().contentlength;
     ldownloadfile=length;
     if (lstartpos>0) 
      request.addrange((int)lstartpos); //设置range值 
    
     //向服务器请求,获得服务器回应数据流 
     system.io.stream ns= request.getresponse().getresponsestream(); 
    
     byte[] nbytes = new byte[512]; 
     int nreadsize=0;    
     nreadsize=ns.read(nbytes,0,512); 
     while( nreadsize >0) 
     { 
      fs.write(nbytes,0,nreadsize); 
      nreadsize=ns.read(nbytes,0,512); 
      lcurrentpos=fs.length; 
   
     } 
    
     fs.close(); 
     ns.close(); 
     strerror="下载完成"; 
    
    } 
    catch(exception ex) 
    { 
     fs.close(); 
     strerror="下载过程中出现错误:"+ ex.tostring(); 
    
    } 
  
   }
  } 
  //定义下载类结束 
新闻热点
疑难解答