0

Hello I'm just learning how to download file using 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;
    }
Bizhan
  • 16,157
  • 9
  • 63
  • 101
zackmark15
  • 657
  • 6
  • 12

1 Answers1

2

Microsoft recommend you don't use HttpWebRequest for new development; use HttpClient instead.

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. I'd probably use Bruno's answer

Caius Jard
  • 72,509
  • 5
  • 49
  • 80