You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中使用HttpClient获取文件下载整数进度的实现咨询

WPF中使用HttpClient下载文件并获取下载进度整数值

原来的CopyToAsync方法没有进度回调能力,要获取下载进度的整数值,需要手动实现流的读写逻辑,结合IProgress<int>传递进度百分比。以下是修改后的完整实现:

修改后的下载方法

public static async Task HttpDownload(string url, string outputLocation, IProgress<int> progress = null)
{
    using (HttpClient client = new HttpClient())
    using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
    {
        response.EnsureSuccessStatusCode();
        long? totalBytes = response.Content.Headers.ContentLength;
        using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
        using (Stream streamToWriteTo = File.Open(outputLocation, FileMode.Create))
        {
            byte[] buffer = new byte[8192];
            long totalReadBytes = 0;
            int readBytes;
            
            while ((readBytes = await streamToReadFrom.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                await streamToWriteTo.WriteAsync(buffer, 0, readBytes);
                totalReadBytes += readBytes;

                // 计算并传递进度百分比(整数值)
                if (totalBytes.HasValue && progress != null)
                {
                    int percentage = (int)((totalReadBytes * 100) / totalBytes.Value);
                    progress.Report(percentage);
                }
            }
        }
    }
}

WPF中调用示例

在UI事件中创建Progress<int>实例,直接在回调中更新进度条(Progress<T>会自动切换到UI线程,无需手动调用Dispatcher):

private async void DownloadButton_Click(object sender, RoutedEventArgs e)
{
    string downloadUrl = "目标文件下载链接";
    string savePath = @"C:\Downloads\targetFile.exe";
    
    var downloadProgress = new Progress<int>(percent =>
    {
        // 直接绑定到WPF的ProgressBar控件
        DownloadProgressBar.Value = percent;
    });

    await HttpDownload(downloadUrl, savePath, downloadProgress);
    MessageBox.Show("下载完成");
}

关键说明

  • 使用HttpCompletionOption.ResponseHeadersRead:先获取响应头(包含文件总大小)再开始下载,避免一次性将整个文件加载到内存
  • 自定义缓冲读写:每次读取固定字节后累加已下载量,计算百分比并转为整数值传递
  • 兼容无Content-Length情况:部分服务器不返回文件大小,此时totalBytes为null,可根据需求添加“进度未知”的提示逻辑

内容的提问来源于stack exchange,提问作者SoapierGlobe421

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:05:26