NEWS

[C#] Hướng dẫn download file with progressbar sử dụng windows console

[C#] Hướng dẫn download file with progressbar sử dụng windows console
Đăng bởi: Thảo Meo - Lượt xem: 5573 08:30:47, 08/07/2021C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục chia sẻ đến các bạn source code cách download file with progress bar trên Windows Console C#.

[C#] Download File with ProgressBar Windows Console

Dưới đây là hình ảnh demo ứng dụng download trên Console:

download_file_console_csharp

Ở hình trên các bạn thấy, khi tải tập tin mình hiển thị các thông tin cơ bản của download file.

  1. Progress bar
  2. Số phần trăm dữ liệu đã được tải
  3. Tốc độ download speed/s
  4. Tổng dung lượng của File download

Video demo download file console c#:

Source code c#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace UpdateHOB
{

    public static class ConsoleWindow
    {
        internal static class Program
        {
            private static async Task Main()
            {

                Console.ForegroundColor = ConsoleColor.Blue;
                var text = @"
                             _             _        _       _          _                 _   
                            | |           | |      (_)     | |        | |               | |  
                            | | __ _ _ __ | |_ _ __ _ _ __ | |____   _| |__   _ __   ___| |_ 
                            | |/ _` | '_ \| __| '__| | '_ \| '_ \ \ / / '_ \ | '_ \ / _ \ __|
                            | | (_| | |_) | |_| |  | | | | | | | \ V /| |_) || | | |  __/ |_ 
                            |_|\__,_| .__/ \__|_|  |_|_| |_|_| |_|\_/ |_.__(_)_| |_|\___|\__|
                                    | |                                                      
                                    |_|                                                                                                                                              
                    ";


                Console.WriteLine(text);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Title = "Update HOB";
                await FileTransferProgressBars();

            }
            private static async Task FileTransferProgressBars()
            {

                List<string> urls = new List<string>();
                urls.Add("https://download.microsoft.com/download/4/6/8/4681f3b2-f327-4d3d-8617-264b20685be0/SSMS-Setup-ENU.exe");

                await TestFileTransferProgressBar(urls);

                Console.ReadLine();
            }

            private static void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw, FileTransferProgressBar progress, int left, int top)
            {

                progress.BytesReceived = e.BytesReceived;
                var speed = string.Format("{0} Kb/s ", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
                var percent = (double)e.BytesReceived / e.TotalBytesToReceive;
                progress.Report(percent, speed);


            }
            public static long GetFileSize(string url)
            {
                long result = -1;

                System.Net.WebRequest req = System.Net.WebRequest.Create(url);
                req.Method = "HEAD";
                using (System.Net.WebResponse resp = req.GetResponse())
                {
                    if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
                    {
                        result = ContentLength;
                    }
                }

                return result;
            }

            public static void ClearCurrentConsoleLine(int currentLineCursor)
            {

                Console.SetCursorPosition(0, currentLineCursor);
                Console.Write(new string(' ', Console.WindowWidth));
                Console.SetCursorPosition(0, currentLineCursor);
            }
            private static async Task TestFileTransferProgressBar(List<string> urls)
            {
                var listTask = new List<Task>();
                await Task.Run(() =>
                {
                    foreach (var item in urls)
                    {
                        Stopwatch sw = new Stopwatch();
                        using (var webClient = new WebClient())
                        {
                            Uri URL = new Uri(item);
                            var totalBytes = GetFileSize(item);
                            var textCaption = $"File {Path.GetFileName(item)} transfer in progress... ";
                            Console.Write(textCaption);
                            int left = Console.CursorLeft;
                            int top = Console.CursorTop;

                            var progress = new FileTransferProgressBar(totalBytes, TimeSpan.FromSeconds(5))
                            {
                                NumberOfBlocks = 20,
                                StartBracket = "|",
                                EndBracket = "|",
                                CompletedBlock = "|",
                                IncompleteBlock = "\u00a0",
                                AnimationSequence = ProgressAnimations.PulsingLine

                            };


                            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw, progress, left, top)); ;

                            sw.Start();
                            try
                            {

                                webClient.DownloadFileAsync(URL, Path.GetFileName(item));
                            }
                            catch (WebException ex1)
                            {
                                Console.WriteLine(ex1.Message);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }

                        }

                    }
                });


            }


        }
    }
}

Trong bài viết có sử thêm thư viện progress bar, các bạn download source ở dưới về để tham khảo và tích hợp vào nhé.

Thanks for watching!

DOWNLOAD SOURCE

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn download file with progressbar sử dụng windows console
Đăng bởi: Thảo Meo - Lượt xem: 5573 08:30:47, 08/07/2021C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.