C#下载大文件用的示例代码

一个很简单的例子
优点:可以显示进度,对于大文件下载较为合适
不足:尚未实现断点续传,也没实现多线程下载

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
//written by nid
namespace bigFileDown
{
class Program
{
private static WebClient client = new WebClient();
private static Point p;
private static long totalbytes;
static void Main(string[] args)
{
StartDownload();
}

private static void StartDownload()
{
try
{
Console.WriteLine("开始下载文件...");
Stream stream = client.OpenRead("http://happy.hustonline.net/");

totalbytes = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
FileStream fs = new FileStream("d:\\test.html", FileMode.OpenOrCreate, FileAccess.Write);

byte[] mbyte = new byte[10000];

int allmybyte = mbyte.Length;
long nowFinish = 0;

int m = stream.Read(mbyte, 0, allmybyte);

Console.WriteLine();
p = new Point();
p.X = Console.CursorLeft;
p.Y = Console.CursorTop;

while (nowFinish < totalbytes || m>0)
{
fs.Write(mbyte, 0, m);
nowFinish += m;

ouput(nowFinish);
m = stream.Read(mbyte, 0, allmybyte);
}

fs.Close();
stream.Close();

Console.WriteLine("下载完毕!");
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());

}
}

private static void ouput(long nowFinish)
{

Console.SetCursorPosition(p.X, p.Y);
Console.WriteLine("{0:f}%,完成:{1},总共:{2}", (double)(nowFinish * 100) / totalbytes, nowFinish, totalbytes);

}
}
}
posted @ 2008-06-12 16:26  冰封的心  阅读(958)  评论(0)    收藏  举报