主页 > 编程资料 > C# >
发布时间:2015-09-26 作者:网络 阅读:266次

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

关键字词: