C#文件下载
闲话少说,直接上源码:
(所写内容为WinForm程序,主要用到WebClient类和普通的数据流操作,两种方法下载,个人实验发现WebClient适合小文件下载,数据流操作适合大文件下载,建议使用方法五 )
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VideoDownLoad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDownLoad_Click(object sender, EventArgs e)
{
string url = "http://www.rthxchina.com/Rfiles/video4.mp4";
WebClient client = new WebClient();
string receivePath = @"D:\Interface\";
#region 第一种 完全下载 中(对超大文件,不适用)
// client.DownloadFile(url, receivePath + System.IO.Path.GetFileName(url));
#endregion
#region 第二种 只能下载一部分(不到1M) 差
//Stream str2 = client.OpenRead(url);
//StreamReader reader = new StreamReader(str2);
//byte[] mbyte = new byte[1000000];
//int allmybyte = (int)mbyte.Length;
//int startmbyte = 0;
//while (allmybyte > 0)
//{
// int m = str2.Read(mbyte, startmbyte, allmybyte);
// if (m == 0)
// break;
// startmbyte += m;
// allmybyte -= m;
//}
//reader.Dispose();
//str2.Dispose();
//string path = receivePath + System.IO.Path.GetFileName(url);
//FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
//fstr.Write(mbyte, 0, startmbyte);
//fstr.Flush();
//fstr.Close();
#endregion
#region 第三种 部分下载 最差
//client.DownloadFile(url, "video1.mp4");
//Stream str = client.OpenRead(url);
//StreamReader reader = new StreamReader(str);
//byte[] mbyte = new byte[100000];
//int allmybyte = (int)mbyte.Length;
//int startmbyte = 0;
//while (allmybyte > 0)
//{
// int m = str.Read(mbyte, startmbyte, allmybyte);
// if (m == 0)
// break;
// startmbyte += m;
// allmybyte -= m;
//}
//try
//{
// FileStream fstr = new FileStream("D:\\Interface\\video1.mp4", FileMode.OpenOrCreate, FileAccess.Write);
// fstr.Write(mbyte, 0, startmbyte);
// str.Close();
// fstr.Close();
// MessageBox.Show("成功下载啦!");
//}
//catch
//{
// MessageBox.Show("..你没装MerDKP插件,群共享里面有插件下载", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// MessageBox.Show("提示:魔兽目录里没有AddOns\\MerDKP目录,请确认安装此插件后再下载");
//}
#endregion
#region 第四种 完全下载 中(对大文件不适用)
//if (client.IsBusy)//是否存在正在进行中的Web请求
//{
// client.CancelAsync();
//}
////开始下载
//client.DownloadFileAsync(new Uri(url), "video4.mp4");
////为webClient添加事件
////client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
////client.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
////开始下载
//// client.DownloadFileAsync(new Uri(url), "video4.mp4");
#endregion
#region 方法五 完全、分段下载 优
// DownloadFile("http://www.rthxchina.com/Rfiles/video4.mp4", receivePath + "1.mp4", progressBar1, label1);
#endregion
}
#region 方法四 注册事件
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//this.progressBar1.Value = e.ProgressPercentage;
//this.lbl_pro.Text = e.ProgressPercentage.ToString() + "%";
//this.lbl_detail.Text = string.Format("正在下载文件,完成进度{0}/{1}(字节)"
// , e.BytesReceived
// , e.TotalBytesToReceive);
}
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
MessageBox.Show("下载被取消!");
else
MessageBox.Show("下载完成!");
}
#endregion
/// <summary>
/// c#,.net 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
///
/// <param name="Filename">下载后的存放地址</param>
/// <param name="Prog">用于显示的进度条</param>
///
#region 流操作 下载
public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
{
float percent = 0;
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (prog != null)
{
prog.Maximum = (int)totalBytes;
}
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
System.Windows.Forms.Application.DoEvents();
so.Write(by, 0, osize);
if (prog != null)
{
prog.Value = (int)totalDownloadedByte;
}
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
label1.Text = "当前补丁下载进度" + percent.ToString() + "%";
System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
}
so.Close();
st.Close();
}
catch (System.Exception)
{
throw;
}
}
#endregion
}
}