- [C#] Dependency Injection in Winform
- [SQLSERVER] Hướng dẫn tìm kiếm nâng cao trên sql
- [C#] Hướng dẫn sử dụng SetTimeOut trên Winform like Javascript
- [DATABASE] In cây thông noel bằng sqlserver
- [C#] Hướng dẫn fix lỗi hiển thị UTF-8 khi sử dụng WebClient Download String
- [DATABASE] Hướng dẫn mã hóa và giải mã sử dụng thuật toán AES 256 trên sqlserver
- [DATABASE] Base64 Encode and Decode trong Sqlserver
- [C#] Vì Mẹ anh bắt phải Fake địa chỉ MacAddress
- [C#] Hướng dẫn xuất dữ liệu từ DataGridview ra file Excel
- [C#] Hướng dẫn khởi động lại chương trình ứng dụng winform
- [C#] Sự khác nhau giữa String.IsNullOrEmpty và String.IsNullOrWhiteSpace
- [C#] Hướng dẫn đọc file hình ảnh định dạng WEBP và chuyển đổi WebP sang JPG
- [C#] Kiểm tra phiên bản Microsoft Office đang sử dụng trên máy tính
- [C#] Hướng dẫn chuyển đổi tập tin hình ảnh XPS sang Bitmap
- [C#] Giới thiệu Component WebView2 của Microsoft
- [C#] Hướng dẫn lưu tất cả hình ảnh từ File Excel vào thư mục window
- [DATABASE] Hướng dẫn import và export hình ảnh image từ Sqlserver
- [DATABASE] Hướng dẫn sử dụng Hàm ASCII trong sqlserver
- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
[C#] Hướng dẫn download file with progressbar sử dụng windows console
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:
Ở 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.
- Progress bar
- Số phần trăm dữ liệu đã được tải
- Tốc độ download speed/s
- 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!