Files

79 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TemuKJD.BLL.Tools
{
public class DownloadBLL
{
public static string downloadFile(string url, string fileName, Control ctrl)
{
if (ctrl == null)
ctrl = new Control();
//string StrFileName = "d:\\wgscd.zip"; //根据实际情况设置
//string StrUrl = "https://files.cnblogs.com/files/wgscd/xxx.zip"; //根据实际情况设置
string StrFileName = fileName;
string StrUrl = url;
//打开上次下载的文件或新建文件
long lStartPos = 0;
System.IO.FileStream fs;
if (System.IO.File.Exists(StrFileName))//另外如果文件已经下载完毕,就不需要再断点续传了,不然请求的range 会不合法会抛出异常。
{
fs = System.IO.File.OpenWrite(StrFileName);
lStartPos = fs.Length;
fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
}
else
{
fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
lStartPos = 0;
}
//打开网络连接
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
if (lStartPos > 0)
{
request.AddRange((int)lStartPos); // 设置Range值
}
System.Net.WebResponse response = request.GetResponse();
//向服务器请求,获得服务器回应数据流
System.IO.Stream ns = response.GetResponseStream();
long totalSize = response.ContentLength;
long hasDownSize = 0;
byte[] nbytes = new byte[512];//521,2048 etc
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, nbytes.Length);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, 512);
hasDownSize += nReadSize;
ctrl.Invoke(new Action(() =>
{
//ctrl.Text = "" + hasDownSize + "/" + totalSize + " (" + (((double)hasDownSize * 100 / totalSize).ToString("0.00")) + "%)"; // 显示下载百分比
ctrl.Text = "正在下载模块 " + ((double)(hasDownSize + lStartPos) * 100 / (totalSize + lStartPos)).ToString("0.00") + "%"; // 显示下载百分比
}));
//Application.DoEvents();
}
fs.Close();
ns.Close();
ctrl.Invoke(new Action(() =>
{
ctrl.Text = "模块下载完成 " + ((double)(hasDownSize + lStartPos) * 100 / (totalSize + lStartPos)).ToString("0.00") + "%"; // 显示下载百分比
}));
return "下载完成";
}
catch (Exception ex)
{
fs.Close();
return "下载过程中出现错误:" + ex.ToString();
}
}
}
}