前面写到 多线程下载,没有写断点续传下载。为了完整性,补写了这篇 ;下面用代码说话
/// <summary>
/// 下载方法(带进度条)
/// </summary>
/// <param name="URL">服务器URL地址</param>
/// <param name="Filename">存放到本地的路径</param>
/// <param name="Prog">进度条</param>
public static void DownFile(string URL, string Filename, ProgressBar Prog)
{
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
Prog.Maximum = (int)totalBytes;
Stream st = myrp.GetResponseStream();
Stream so = new FileStream(Filename, 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;
Application.DoEvents();
so.Write(by, 0, osize);
Prog.Value = (int)totalDownloadedByte;
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
MessageBox.Show("下载完毕!", "下载提示:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button1);
}
方法二:
////打开上次下载的文件或新建文件
//long lStartPos = 0;
//FileStream fs;
//if (File.Exists(Filename))
//{
// fs = File.OpenWrite(Filename);
// lStartPos = fs.Length;
// fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
//}
//else
//{
// fs = new FileStream(Filename, FileMode.Create);
// lStartPos = 0;
//}
//try
//{
// HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL);
// if (lStartPos > 0)
// Myrq.AddRange((int)lStartPos); //设置Range值
// HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
// long totalBytes = myrp.ContentLength;
// Prog.Maximum = (int)totalBytes;
// Stream st = myrp.GetResponseStream();
// Stream so = new FileStream(Filename, 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;
// Application.DoEvents();
// so.Write(by, 0, osize);
// Prog.Value = (int)totalDownloadedByte;
// osize = st.Read(by, 0, (int)by.Length);
// }
// so.Close();
// st.Close();
// MessageBox.Show("下载完毕!", "下载提示:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,
// MessageBoxDefaultButton.Button1);
//}
}