gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
net core 断点下载
- User
net core 断点下载
- Assistant
在 .NET Core 中,可以使用 HttpClient 来实现断点下载。以下是一个简单的示例:
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public class Program { static async Task Main(string[] args) { string url = "https://example.com/file.txt"; string filePath = "path/to/save/file.txt"; using (HttpClient client = new HttpClient()) { // 检查本地文件是否存在,以确定是否需要启用断点下载 bool isResumable = File.Exists(filePath); if (isResumable) { // 获取已下载文件的大小 long existingFileSize = new FileInfo(filePath).Length; // 添加 Range 请求头,指定已下载的部分的范围 client.DefaultRequestHeaders.Add("Range", $"bytes={existingFileSize}-"); } using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)) { if (response.IsSuccessStatusCode) { using (Stream contentStream = await response.Content.ReadAsStreamAsync()) { using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None)) { // 将响应内容写入到文件中 await contentStream.CopyToAsync(fileStream); } } } else { Console.WriteLine($"HTTP request failed with status code {response.StatusCode}"); } } } } }