C#断点续传的实现
断点续传的实现方式有很多,下面介绍个依赖本地以下载的文件大小来实现断点续传
public static void HttpDownloadEx(string url,
string path,
bool overwrite,
Action<string, HttpWebResponse> doneCallback = null,
Action<string, string, long, long> downloadingCallback = null)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string contentType = response.Headers["Content-Type"];
//断点续传
FileStream fStream = null;
long sPosition = 0;
Stream responseStream = null;
try
{
long totalLength = response.ContentLength;
if (System.IO.File.Exists(path))
{
fStream = System.IO.File.OpenWrite(path);
sPosition = fStream.Length;
if (sPosition == totalLength)
{
doneCallback?.Invoke(path, response); //文件是完整的,直接结束下载任务
return;
}
fStream.Seek(sPosition, SeekOrigin.Current);
}
else
{
fStream = new FileStream(path, FileMode.Create);
sPosition = 0;
}
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (sPosition > 0)
{
myRequest.AddRange(sPosition); //设置Range值
}
//向服务器请求,获得服务器的回应数据流
responseStream = myRequest.GetResponse().GetResponseStream();
//定义一个字节数据
byte[] btContent = new byte[512];
int intSize = 0;
intSize = responseStream.Read(btContent, 0, 512);
while (intSize > 0)
{
fStream.Write(btContent, 0, intSize);
intSize = responseStream.Read(btContent, 0, 512);
downloadingCallback?.Invoke(path, contentType, totalLength, fStream.Length);
}
}
catch
{//(Exception ex)
throw;
}
finally
{
//关闭流
if (responseStream != null)
{
responseStream.Close();
responseStream.Dispose();
}
if (fStream != null)
{
fStream.Close();
fStream.Dispose();
}
}
}
参考文章:http://blog.ncmem.com/wordpress/2023/11/12/c%e6%96%ad%e7%82%b9%e7%bb%ad%e4%bc%a0%e7%9a%84%e5%ae%9e%e7%8e%b0/
欢迎入群一起讨论