简体   繁体   English

使用带有 ProgressBar 的 HttpClient 下载文件

[英]Download file using HttpClient with ProgressBar

Hello I'm just learning how to download file using httpclient.您好,我正在学习如何使用 httpclient 下载文件。 Can anybody help me update my progressbar?有人可以帮我更新我的进度条吗? The download is working but not the progressbar.下载正常,但进度条不正常。

My code for progressbar isnt't working it's not updating我的进度条代码不起作用它没有更新

async Task<string> GetWebSource(string url, string outputpath)
    {
        int count = 0;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallback);
        string result = string.Empty;
        try
        {
            HttpWebRequest request = await Task.Run(() => (HttpWebRequest)WebRequest.Create(url));
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.Proxy = null;
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36";
     
            string output = Path.Combine(outputpath, GetFilenameFromUrl(url));

            using (var httpWebResponse = await Task.Run(() => request.GetResponseAsync()))
            {
                using (var file = new FileStream(output, FileMode.Create, FileAccess.Write))
                {
                    await Task.Run(() => httpWebResponse.GetResponseStream().CopyTo(file));

                    count++;
                    progressBar1.Value = (int)(count / (double)httpWebResponse.ContentLength * 100);
                }
            }

            if (request != null)
            {
                request.Abort();
            }
        }
        catch (Exception)
        {
        }
        return result;
    }

Microsoft recommend you don't use HttpWebRequest for new development;微软建议你不要使用 HttpWebRequest进行新的开发; use HttpClient instead.改用 HttpClient。

When you use HttpClient you can get progress like this: Progress bar with HttpClient - essentially to read the stream yourself gradually and calculate how far you've read compared to the content length declared in the header.当您使用 HttpClient 时,您可以获得这样的进度: 使用 HttpClient 的进度条- 本质上是逐步阅读 stream 并计算与 header 中声明的内容长度相比您已阅读的距离。 I'd probably use Bruno's answer我可能会使用布鲁诺的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM