在C#中处理大文件下载通常需要考虑以下几个方面:
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);
}
}
}
}
}
}
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);
}
}
}
}
}
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);
}
}
}
}
}
}
通过以上方法,可以在C#中高效地处理大文件下载,并且可以根据需要实现断点续传等功能。