首页 > 开发 > 综合 > 正文

C#下载文件函数

2024-07-21 02:25:59
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • using system;
    using system.drawing;
    using system.collections;
    using system.componentmodel;
    using system.windows.forms;
    using system.net;
    using system.io;
    using system.text;

     

    private void button3_click(object sender, system.eventargs e)
      {
       string downloadurl=textbox3.text;
       string localpath=textbox4.text;
       if(downfile(downloadurl,localpath))
       {
       messagebox.show("下载完成");
       }
       else
       {
       messagebox.show("下载过程中出现错误:");
       }
      }
      public bool downfile(string url,string localpath)
      {
       try
       {
        uri u = new uri(url);
        httpwebrequest mrequest = (httpwebrequest)webrequest.create(u);
        mrequest.method = "get";
        mrequest.contenttype = "application/x-www-form-urlencoded";

        httpwebresponse wr = (httpwebresponse)mrequest.getresponse();

        stream sin = wr.getresponsestream();
        filestream fs = new filestream(localpath, filemode.create, fileaccess.write);

        long length = wr.contentlength;
        long i = 0;
        decimal j=0;
        
        while (i < length)
        {
         byte[] buffer = new byte[1024];
         i += sin.read(buffer, 0, buffer.length);
         fs.write(buffer, 0, buffer.length);
         
         if((i % 1024)==0)
         {
          j=math.round(convert.todecimal((convert.todouble(i)/convert.todouble(length))*100),4);
          statusbar1.text="当前下载文件大小:"+length.tostring()+"字节   当前下载大小:"+i+"字节 下载进度"+j.tostring()+"%";
          
         }
         else
         {
          statusbar1.text="当前下载文件大小:"+length.tostring()+"字节   当前下载大小:"+i+"字节";
         }
         
        }

        sin.close();
        wr.close();
        fs.close();
        return true;
       }
       catch { return false; }
      } 

    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表