代码
#region 文件下载
/// <summary>
/// 下载文件
/// </summary>
/// <param name="url">文件下载地址</param>
/// <param name="savePath">本地保存路径+名称</param>
/// <param name="downloadCallBack">下载回调(总长度,已下载,进度)</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task DownloadFileAsync(string url, string savePath, Action<long, long, double>? downloadCallBack = null)
{
try
{
Console.WriteLine($"文件【{url}】开始下载!");
HttpResponseMessage? response = null;
using (HttpClient client = new HttpClient())
response = await client.GetAsync(url);
if (response == null)
throw new Exception("文件获取失败");
var total = response.Content.Headers.ContentLength ?? 0;
var stream = await response.Content.ReadAsStreamAsync();
var file = new FileInfo(savePath);
using (var fileStream = file.Create())
using (stream)
{
if (downloadCallBack == null)
{
await stream.CopyToAsync(fileStream);
Console.WriteLine($"文件【{url}】下载完成!");
}
else
{
byte[] buffer = new byte[1024];
long readLength = 0;
int length;
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
// 写入到文件
fileStream.Write(buffer, 0, length);
//更新进度
readLength += length;
double? progress = Math.Round((double)readLength / total * 100, 2, MidpointRounding.ToZero);
lock (lockObj)
{
//下载完毕立刻关闭释放文件流
if (total == readLength && progress == 100)
{
fileStream.Close();
fileStream.Dispose();
}
downloadCallBack?.Invoke(total, readLength, progress ?? 0);
}
}
}
}
}
catch (Exception ex)
{
throw new Exception($"下载文件失败:{ex.Message}!");
}
}
#endregion
测试
评论区