C# Response如何处理大文件下载
原文链接:https://www.yisu.com/ask/18923534.html
在C#中处理大文件下载通常需要考虑以下几个方面:
1、使用流(Stream)来处理大文件下载,可以有效避免一次性加载整个文件到内存中,节约内存资源。可以使用HttpWebRequest或HttpClient来获取文件的流,然后逐块下载文件内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using System; using System.IO; using System.Net; public class FileDownloader { public void DownloadFile( string url, string savePath) { using ( var client = new WebClient()) { using ( var stream = client.OpenRead(url)) { using ( var fileStream = new FileStream(savePath, FileMode.Create)) { byte [] buffer = new byte [4096]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } } } } } |
2、使用异步下载来提高下载性能,可以使用HttpClient的异步方法来下载文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public class FileDownloader { public async Task DownloadFileAsync( string url, string savePath) { using ( var client = new HttpClient()) { using ( var stream = await client.GetStreamAsync(url)) { using ( var fileStream = new FileStream(savePath, FileMode.Create)) { await stream.CopyToAsync(fileStream); } } } } } |
3、考虑断点续传功能,可以在下载过程中记录已经下载的文件大小,以便在下载中断后可以继续下载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class FileDownloader { public async Task DownloadFileWithResumeAsync( string url, string savePath) { long fileSize = 0; if (File.Exists(savePath)) { fileSize = new FileInfo(savePath).Length; } using ( var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(fileSize, null ); using ( var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { using ( var stream = await response.Content.ReadAsStreamAsync()) { using ( var fileStream = new FileStream(savePath, FileMode.Append)) { await stream.CopyToAsync(fileStream); } } } } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了