html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

C#下载文件函数_.NET教程_编程技术

[ ] 已经帮助:人解决问题
函数|下载

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; }
  } 

6GxHTML5中文学习网 - HTML5先行者学习网
6GxHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助