国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 宜兰市| 南华县| 辰溪县| 泽库县| 思茅市| 容城县| 桂阳县| 襄汾县| 佛冈县| 建宁县| 西青区| 阜城县| 东港市| 清流县| 和林格尔县| 兴义市| 洛川县| 大渡口区| 永善县| 平顶山市| 舟山市| 秦安县| 清新县| 石泉县| 滨海县| 漳州市| 九龙坡区| 班玛县| 安平县| 通榆县| 聊城市| 讷河市| 尚志市| 新平| 台南县| 白玉县| 睢宁县| 乐昌市| 凤城市| 阳泉市| 芷江|