在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#中高效地處理大文件下載,并且可以根據需要實現斷點續傳等功能。