最近因为开发一个项目需要使用到http文件下载功能,在网络上搜索,发现大部分都是本地另存为类型的下载,只适用于不同的磁盘之间进行文件更新操作,找到的一些适用于http文件下载的源代码,不是不完整,就是有错误,经过小编的不懈努力,借鉴了一些源代码功能,成功实现了http文件下载,这里把源代码贴出来,希望能帮到需要的朋友
文件下载工具
开发工具 VS2010
开发语言 C#
开发框架 .NET4.0
功能说明:源地址一栏是要下载的http文件的URL地址,另存为一栏是要保存的地址路径
举例:源地址:http://weisico.com/program/2015/0630/237.html
另存为:d:\test\
源代码
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
namespace filedownload
{
public partial class Form1 : Form
{
private WebClient client = new WebClient();
public Form1()
{
InitializeComponent();
}
private void start_Click(object sender, EventArgs e)
{
if (srcAddress.Text == "" || tarAddress.Text == "")
{
MessageBox.Show("下载源地址和目标地址不能为空");
}
else
{
Thread th = new Thread(new ThreadStart(StartDownload));
th.Start();
}
}
private void StartDownload()
{
string URL = srcAddress.Text;
int n = URL.LastIndexOf("/");
string URLAddress = URL;//.Substring(0, n);
string fileName = URL.Substring(n + 1, URL.Length - n - 1);
string Dir = tarAddress.Text;
//下载文件,直接覆盖
string Path = Dir + fileName;
//Datetime.Now.ToFileTime.ToString()用于区别下载时间
// string Path = Dir +DateTime.Now.ToFileTime().ToString() + fileName ;
try
{
WebRequest myre = WebRequest.Create(URLAddress);
Stream stream = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(stream);
FileStream outputStream = new FileStream(Path, FileMode.OpenOrCreate);
try
{
int bufferSize = 100; // 网络速度快的话可以设置大一点,慢的话可以小一点
int nRealCount;
byte[] bBuffer = new byte[bufferSize];
nRealCount = stream.Read(bBuffer, 0, bufferSize);
// 下载,一面读一面下载是最好的方式。这样就不用声明多大的数组了
while (nRealCount > 0)
{
outputStream.Write(bBuffer, 0, nRealCount);
nRealCount = stream.Read(bBuffer, 0, bBuffer.Length);
}
MessageBox.Show("下载完毕!");
}
catch (WebException exp)
{
MessageBox.Show(exp.Message, "Error");
this.Text = "";
}
finally
{
stream.Close();
reader.Close();
outputStream.Close();
}
//Application.Exit();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
//MessageBox.Show("请输入正确的文件地址");
}
}
}
}
该下载工具功能比较单一,欢迎热衷分享技术的朋友,进一步完善,交流,E-mail:webmaster@weisico.com