- [C#] Hướng dẫn giải nén file *.rar với tiến trình progress bar winform
- [C#] Chia sẻ source code make Crazy Error Message Effect Bomb Windows
- [C#] Lập trình ứng dụng theo mô hình MVP Model-View-Presenter Pattern Winform
- [C#] Giới thiệu và những thứ hay ho từ thư viện System.Reactive của Microsoft
- [C#] Hướng dẫn tạo ứng dụng Chat với GPT sử dụng Open AI API
- [DEVEXPRESS] Tạo month picker trên DateEdit Winform C#
- [DATABASE] Cách sử dụng và lưu ý khi sử dụng khóa ngoại (Foreign Key) trong Sqlserver
- [C#] Garbage Collector (GC) là gì? Cách giải phóng bộ nhớ trên ứng dụng Winform khi các đối tượng không còn sử dụng
- [C#] Cách tính độ tương phản màu sắc Contrast Color mà con người có thể nhìn thấy được
- [C#] Hướng dẫn mã hóa mật khẩu tài khoản ứng dụng đúng chuẩn Men
- [C#] Sử dụng Open AI Chat GPT viết ứng dụng Count down timer có hiệu ứng trên winform
- [DATABASE] Chia sẻ dữ liệu Pantone Color sql và json api
- [SQLSERVER] Tạo mã sản phẩm tự động như: SP0001, SP0002, SP0003... sử dụng Trigger
- [C#] Hướng dẫn kiểm tra phiên bản NET Framework cài đặt ở máy tính
- [C#] Hướng dẫn đọc file excel đơn giản sử dụng thư viện Epplus
- [C#] ConcurrentBag là gì và cách sử dụng nó trong lập trình bất đồng bộ
- [C#] AutoResetEvent là gì và cách sử dụng
- [DEVEXPRESS] Chia sẻ source code cách tạo biểu đồ sơ đồ tổ chức công ty Org Chart trên Winform C#
- [C#] Hướng dẫn tạo Auto Number trên Datagridview winform
- [DATABASE] Hướng dẫn tạo Procedure String Split in Mysql
[C#] Chia sẻ soure code download multi file with Guna UI
Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code Tải nhiều file sử dụng Guna UI 2 để thiết kế giao diện.
[C#] Source code Download Multi file
Source code này lúc trước mình làm ở công ty, viết tool cho chức năng tự động cập nhật phần mềm.
Nay mình chia sẻ cho các bạn nào cần có thể tải về và custom lại để sử dụng.
Bạn nào chưa có thư viện, Guna hoặc Active Click vào link này nhé.
Source code C#:
using Guna.UI2.WinForms.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UpdateHOB
{
public partial class FrmUpdateApp : Form
{
public int NUM_TASK = 4;
public string APP_NAME = "LAPTRINHVB.NET";
private int TOTAL_FILE_DOWNLOAD = 0;
private int FILE_DOWNLOAD_FINISH = 0;
public List<FileUpdateInfo> listFileUpdate;
public string main_file = "";
public FrmUpdateApp()
{
InitializeComponent();
guna2ShadowForm1.SetShadowForm(this);
this.DoubleBuffered = true;
this.Shown += FrmUpdateApp_Shown;
}
public List<FileUpdateInfo> Get_DanhSach_File_Download()
{
var listFileDownload = new List<FileUpdateInfo>();
var file1 = new FileUpdateInfo();
file1.tenfile = "https://download.microsoft.com/download/8/a/8/8a8073d2-2e00-472b-9a18-88361d105915/SSMS-Setup-ENU.exe";
file1.local_file = "SSMS-Setup-ENU";
var file2 = new FileUpdateInfo();
file2.tenfile = "https://res-download-pc-te-vnso-pt-5.zadn.vn/hybrid/ZaloSetup-22.9.2.exe";
file2.local_file = "Zalo-setup.exe";
var file3 = new FileUpdateInfo();
file3.tenfile = "https://r4---sn-8qj-nbo66.gvt1.com/edgedl/android/studio/install/2021.3.1.16/android-studio-2021.3.1.16-windows.exe";
file3.local_file = "Android Studio";
listFileDownload.Add(file1);
listFileDownload.Add(file2);
listFileDownload.Add(file3);
return listFileDownload;
}
private async void FrmUpdateApp_Shown(object sender, EventArgs e)
{
PanelScrollHelper vScrollHelper = new PanelScrollHelper(flowLayoutPanel1, guna2VScrollBar, true);
var source = new CancellationTokenSource();
CancellationToken ct = source.Token;
listFileUpdate = Get_DanhSach_File_Download();
var list = new ItemDownload[listFileUpdate.Count];
int i = 0;
foreach (var item in listFileUpdate)
{
list[i] = new ItemDownload();
list[i].SuspendLayout();
list[i].Stt = i + 1;
var fileName = Path.GetFileName(item.tenfile);
list[i].FileName = item.local_file;
list[i].ServerTime = item.server_time;
list[i].LocalURL = item.local_file;
list[i].ServerURL = item.tenfile;
list[i].Progress = 0;
list[i].SizeDownload = "0 Kb/s";
list[i].Status = "Sẵn sàng";
list[i].Name = fileName;
list[i].ResumeLayout();
i++;
}
flowLayoutPanel1.SuspendLayout();
flowLayoutPanel1.Controls.AddRange(list);
flowLayoutPanel1.ResumeLayout();
guna2VScrollBar.Size = new Size(8, 250);
vScrollHelper.UpdateScrollBar();
TOTAL_FILE_DOWNLOAD = listFileUpdate.Count;
this.BringToFront();
var progress = new Progress<int>(percent =>
{
progressBarTotal.Value = percent;
if (FILE_DOWNLOAD_FINISH >= TOTAL_FILE_DOWNLOAD)
{
progressBarTotal.Value = 100;
}
});
await Task.Run(() => DownloadListFileUpdate(listFileUpdate, progress, ct));
}
public List<List<FileUpdateInfo>> SplitList(List<FileUpdateInfo> locations, int nSize = 8)
{
var list = new List<List<FileUpdateInfo>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}
public void DownloadListFileUpdate(List<FileUpdateInfo> listFileUpdate, IProgress<int> progress, CancellationToken ct)
{
FILE_DOWNLOAD_FINISH = 0;
SemaphoreSlim maxThread = new SemaphoreSlim(NUM_TASK);
foreach (ItemDownload fileupdate in flowLayoutPanel1.Controls)
{
Task.Factory.StartNew(() =>
{
int index = listFileUpdate.FindIndex(a => a.tenfile == fileupdate.FileName);
var lastModifiedServer = fileupdate.ServerTime;
DownloadFile(fileupdate.ServerURL, fileupdate.LocalURL, index, lastModifiedServer, fileupdate);
}, TaskCreationOptions.LongRunning).ContinueWith((task) => maxThread.Release());
}
}
public void DownloadFile(string urlAddress, string location, int rowHandle, DateTime lastModifiedServer, ItemDownload itemDownload)
{
Stopwatch sw = new Stopwatch();
using (var webClient = new WebClient())
{
var fileName = Path.GetFileName(urlAddress);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => Completed(sender, e, fileName, sw, lastModifiedServer, location, itemDownload));
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, fileName, sw, itemDownload));
Uri URL = new Uri(urlAddress);
sw.Start();
try
{
webClient.DownloadFileAsync(URL, location);
}
catch (WebException ex1)
{
MessageBox.Show(ex1.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public class CallBackData
{
public int progress { set; get; }
public string size { set; get; }
public string speed { set; get; }
public string status { set; get; }
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, string fileName, Stopwatch sw, ItemDownload itemDownload)
{
var callBackData = new CallBackData();
callBackData.progress = e.ProgressPercentage;
callBackData.size = string.Format("{0} / {1} MB",
(e.BytesReceived / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
callBackData.status = "Đang tải...";
callBackData.speed = string.Format("{0} Kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
UpdateProgressByFileName(fileName, callBackData);
}
private void Completed(object sender, AsyncCompletedEventArgs e, string fileName, Stopwatch sw, DateTime lastModifined, string FileDownloaded, ItemDownload itemDownload)
{
if (e.Cancelled == true)
{
UpdateProgressByRowHandle(fileName, "status", "Lỗi");
sw.Stop();
}
else
{
try
{
File.SetLastWriteTime(FileDownloaded, lastModifined);
}
catch (Exception)
{
}
var callBackData = new CallBackData();
callBackData.progress = 100;
callBackData.status = "Hoàn thành";
UpdateProgressByFileName(fileName, callBackData);
flowLayoutPanel1.BeginInvoke(new Action(() =>
{
flowLayoutPanel1.Controls.Remove(itemDownload);
}));
sw.Stop();
}
Thread.Sleep(10);
Interlocked.Increment(ref FILE_DOWNLOAD_FINISH);
double percent = Convert.ToDouble(FILE_DOWNLOAD_FINISH) / Convert.ToDouble(TOTAL_FILE_DOWNLOAD) * 100.0;
int value = Convert.ToInt32(percent);
progressBarTotal.Value = value;
lbl_danhsach.BeginInvoke(new Action(() =>
{
lbl_danhsach.Text = $"Danh sách tập tin cập nhật ({FILE_DOWNLOAD_FINISH}/{TOTAL_FILE_DOWNLOAD})";
}));
if (value >= 100)
{
var timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Enabled = true;
timer.Elapsed += Timer1_Tick;
}
}
int s = 0;
public void Timer1_Tick(object sender, EventArgs e)
{
s++;
if (s == 2)
{
if (main_file != "")
{
Thread.Sleep(500);
Process.Start(main_file);
Thread.Sleep(100);
Process.GetCurrentProcess().Kill();
}
}
}
private void UpdateProgressByFileName(string fileName, CallBackData callBackData)
{
ItemDownload itemDownload = flowLayoutPanel1.Controls[fileName] as ItemDownload;
itemDownload.SETDATA(callBackData);
}
private void UpdateProgressByRowHandle(string fileName, string column, string message)
{
Console.WriteLine(message);
ItemDownload itemDownload = flowLayoutPanel1.Controls[fileName] as ItemDownload;
itemDownload.BeginInvoke(new Action(() =>
{
if (column == "progress")
{
var progress = Convert.ToInt32(message);
itemDownload.Progress = progress;
}
else if (column == "speed")
{
itemDownload.Speed = message;
}
else if (column == "size")
{
itemDownload.SizeDownload = message;
}
else if (column == "status")
{
itemDownload.Status = message;
}
}));
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
private void FrmUpdateApp_Load(object sender, EventArgs e)
{
}
}
public class FileUpdateInfo
{
public string tenfile { set; get; }
public string local_file { set; get; }
public DateTime server_time { set; get; }
public bool is_main { set; get; }
public int progress { set; get; } = 0;
public string status { set; get; } = "Sẵn sàng";
public string speed { set; get; } = "";
public string size { set; get; } = "";
public string filename
{
get
{
return Path.GetFileName(tenfile);
}
}
}
}
Thanks for watching!