国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

C#用線程傳參下載文件的代碼

2024-07-21 02:26:00
字體:
供稿:網(wǎng)友

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;

private void button6_click(object sender, system.eventargs e)
  {
   //定義一個類
   //實例化一個線程對象
   //實例類對象賦值
   downloadclass a=new downloadclass(); 
   thread thread2 = new thread(new threadstart(a.downloadfile));
   a.strurl=textbox1.text;
   a.strfilename=textbox2.text;
   thread2.start();
   if(thread2.join(500))
    {
    messagebox.show(a.strerror);
    }   
   
  }

  
  //測試用線程1斷點續(xù)傳下載網(wǎng)絡(luò)上的文件到本地電腦
  public class downloadclass
  {  
   //打開上次下載的文件或新建文件
   public string strurl;//文件下載網(wǎng)址
   public string strfilename;//下載文件保存地址
   public string strerror;//返回結(jié)果
   public long lstartpos =0; //返回上次下載字節(jié)
   public long lcurrentpos=0;//返回當(dāng)前下載字節(jié)
   public long ldownloadfile;//返回當(dāng)前下載文件長度

   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);
     //移動文件流中的當(dāng)前指針
    }
    else
    {
     fs = new system.io.filestream(strfilename,system.io.filemode.create);
     lstartpos =0;
    }

    //打開網(wǎng)絡(luò)連接
    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); //設(shè)置range值
    
     //向服務(wù)器請求,獲得服務(wù)器回應(yīng)數(shù)據(jù)流
     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="下載過程中出現(xiàn)錯誤:"+ ex.tostring();
    
    }
  
   }
  } 
  //定義下載類結(jié)束 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 巴中市| 珲春市| 城步| 海口市| 大宁县| 郁南县| 鲁甸县| 始兴县| 科尔| 沈丘县| 通道| 兴化市| 永城市| 东方市| 申扎县| 元谋县| 海伦市| 北宁市| 咸宁市| 宝山区| 武乡县| 玉门市| 彭山县| 永泰县| 普兰店市| 习水县| 绥中县| 达孜县| 芮城县| 祁阳县| 榆林市| 新民市| 望江县| 磐安县| 济宁市| 潍坊市| 祁东县| 北票市| 瑞昌市| 萨嘎县| 盘山县|