Progressbar
trên Console App
C#.[C#] Download File with progressbar in Shell Console App
Để hiển thị progresbar trong bài này mình sẻ sử dụng thư viện
ShellProgressBar version 5.2
Các bạn, cài đặt từ Nuget với lệnh sau:
NuGet\Install-Package ShellProgressBar -Version 5.2.0
Project của các bạn phải
target NetFramework từ 4.6
trở lên nhé.Giao diện demo ứng dụng download file with progressbar Shell console c#:
Source code c#:
using ShellProgressBar; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace progressBarConsole { internal class Program { static async Task Main(string[] args) { await StartAsync(); } protected static Task StartAsync() { var files = new string[] { "https://github.com/Mpdreamz/shellprogressbar/archive/4.1.0.zip", "https://github.com/Mpdreamz/shellprogressbar/archive/4.0.0.zip", "https://download.microsoft.com/download/8/a/8/8a8073d2-2e00-472b-9a18-88361d105915/SSMS-Setup-ENU.exe", "https://r1---sn-8qj-nbo6y.gvt1.com/edgedl/android/studio/install/2021.3.1.17/android-studio-2021.3.1.17-windows.exe?mh=P9&pl=21&shardbypass=sd&redirect_counter=1&rm=sn-i3b6d7l&req_id=e4e35ad8c06bf917&cms_redirect=yes&cmsv=e&ipbypass=yes&mip=113.161.94.127&mm=28&mn=sn-8qj-nbo6y&ms=nvh&mt=1669251971&mv=u&mvi=1", }; var childOptions = new ProgressBarOptions { ForegroundColor = ConsoleColor.Cyan, // ProgressCharacter = '\u2593', EnableTaskBarProgress= true, ShowEstimatedDuration= true, DisplayTimeInRealTime= true, }; var pbar = new ProgressBar(files.Length, "downloading"); foreach (var (file, i) in files.Select((f, i) => (f, i))) { byte[] data = null; var child = pbar.Spawn(100, "URL: " + file, childOptions); try { var client = new WebClient(); client.DownloadProgressChanged += (o, args) => child.Tick(args.ProgressPercentage); client.DownloadDataCompleted += (o, args) => data = args.Result; client.DownloadDataAsync(new Uri(file)); while (client.IsBusy) { Thread.Sleep(1); } pbar.Tick(); } catch (WebException error) { pbar.WriteLine(error.Message); } } return Task.CompletedTask; } } }
Cảm ơn các bạn đã xem.
Chúc các bạn thành công với thủ thuật này.