C#断点续传,支持回传下载进度、停止

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GadgetUtil.Common
{
/// <summary>
///
/// </summary>
/// <param name="filepath">文件路径</param>
/// <param name="originLength">文件原始长度</param>
/// <param name="current">当前传输的长度</param>
/// <param name="fileLength">当前文件的总长度</param>
/// <param name="total">服务器文件长度</param>
public delegate void DownloadProgress(string filepath, long originLength, long current, long fileLength, long total);

public class FileUtil
{
private bool _isStop;
public void StopDownload()
{
_isStop = true;
}

/// <summary>
/// 断点续传
/// </summary>
/// <param name="url">下载地址</param>
/// <param name="localPath">文件保存路径</param>
public async Task<bool> ResumeDownload(string url, string localPath, DownloadProgress downloadPregress = null)
{
return await Task.Run(() =>
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = int.MaxValue;
long startPosition = 0;
if (File.Exists(localPath))
{
using (FileStream localFileStream = new FileStream(localPath, FileMode.OpenOrCreate))
{
// 如果本地文件已经存在,则获取已经下载的数据长度
startPosition = localFileStream.Length;
request.AddRange((int)startPosition); // 设置http请求头中的Range属性,以便服务器知道需要返回哪些数据
}
}
// 发送请求,获取服务器响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();

// 使用文件流和网络流进行数据读写
long downloadedLen = 0;
using (FileStream localFileStream = new FileStream(localPath, FileMode.OpenOrCreate))
{
localFileStream.Seek(startPosition, SeekOrigin.Current); // 将文件指针指向应该开始下载的位置
byte[] buffer = new byte[1024];
int len;
while ((len = responseStream.Read(buffer, 0, buffer.Length)) != 0)
{
if (_isStop)
return false;
// 写入本地文件
localFileStream.Write(buffer, 0, len);
localFileStream.Flush();
downloadedLen += len;
downloadPregress?.Invoke(localPath, startPosition, len, localFileStream.Length, response.ContentLength + startPosition);
}
}
}
catch
{
return false;
}
return true;
});
}
}
}

posted @   抠脚大汉的脚  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示