您的位置:首页 > 编程语言 > C#

C#中使用WebClient对象下载文件

2008-10-13 18:08 579 查看
/// <summary>
/// 下载文件
/// </summary>
/// <param name="sourceFileUrl"></param>
/// <param name="savePath"></param>
private void ActionDownLoadFile(string sourceFileUrlAddress, string savePath)
{
string fileName = "";
byte[] mbyte = new byte[51200];
int allmybyte = mbyte.Length;
long nowFinish = 0;
int m = 0;
//写入到BYTE数组中,起缓冲作用
FileStream fstr = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
int lastSplitChar = sourceFileUrlAddress.LastIndexOf("/");
WebClient client = new WebClient();
Stream str = null;
long totalbytes = 0;

try
{
this.ShowActionText("链接下载文件...");
fileName = sourceFileUrlAddress.Substring(lastSplitChar + 1); //获得文件名
client.DownloadFile(sourceFileUrlAddress, fileName);
str = client.OpenRead(sourceFileUrlAddress);
totalbytes = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
while (nowFinish < totalbytes || m > 0)
{
m = str.Read(mbyte, 0, allmybyte);
fstr.Write(mbyte, 0, m);
this.ShowActionText("正在接收数据... " + string.Format("{0:f}%,完成:{1},总共:{2} 字节", (double)(nowFinish * 100) / totalbytes, nowFinish, totalbytes));
if (m == 0)
break;
nowFinish += m;
}
str.Close();
fstr.Close();
this.ShowActionText("下载完毕!");
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
}

调用如下: ActionDownLoadFile("http://www.abc123.com/logo.jpg","E:/logo.jpg");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: