侧边栏壁纸
博主头像
怪客のBlog 博主等级

行动起来,活在当下

  • 累计撰写 35 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
C#

C# 使用HttpClient下载文件

怪客
2023-01-18 / 0 评论 / 0 点赞 / 314 阅读 / 0 字

代码

        #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

测试

image-1674012441874
image-1674012531336

0

评论区