Method of downloading files and reporting progress at the same time by dotnet through HttpClient

This article tells you a simple way to download files through HttpClient and report the progress of downloading.

Content Length of HttpClient can often get the length of downloaded content, and ReadAsync can return the current length of read, adding the length of read to the length of downloaded content.

It looks simple, so I just give it to the code.

       private static async Task DownloadFile(string url, FileInfo file)
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync(url);

            try
            {
                var n = response.Content.Headers.ContentLength;
                var stream = await response.Content.ReadAsStreamAsync();
                using(var fileStream = file.Create())
                using (stream)
                {
                    byte[] buffer = new byte[1024];
                    var readLength = 0;
                    int length;
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        readLength += length;

                        Console.WriteLine("Download progress" + ((double)readLength) / n * 100);

                        // Write to a file
                        fileStream.Write(buffer, 0, length);
                    }
                }
            
            }
            catch (Exception e)
            {
            }
        }

If you don't need to get progress, the easiest way is to

                var stream = await response.Content.ReadAsStreamAsync();
                using(var fileStream = file.Create())
                using (stream)
                {
                    await stream.CopyToAsync(fileStream);
                }

I set up my own blog https://blog.lindexi.com/ Welcome to visit, there are many new blogs. Only when I see blogs mature will they be placed in csdn or blog park, but once they are published, they will not be updated.

If you see anything in your blog that you don't understand, welcome to communicate. I built it. dotnet Welcome to join us


This work adopts Knowledge Sharing Signature - Noncommercial Use - Sharing 4.0 International Licensing Agreement in the Same Way License. Reprint, use and redistribute are welcome, but the article signature must be retained. Lin De Xi (Contains links: http://blog.csdn.net/lindexi_gd) and may not be used for commercial purposes. Work modified in this article must be released under the same license. If you have any questions, please contact me. contact.

Added by jameslloyd on Sat, 05 Oct 2019 22:56:47 +0300