Windows Forms: How to Download a File from Internet in C#
By FoxLearn 6/25/2017 8:17:45 PM 14.57K
How to Download a File from Internet with the Progress Bar in C# using webclient
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DownloadDemo" and then click OK
Step 2: Design your form as below
Step 3: Add code to handle your form as below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace DownloadDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } WebClient client; private void btnDownload_Click(object sender, EventArgs e) { //Run download file with multiple thread string url = txtUrl.Text; if (!string.IsNullOrEmpty(url)) { Thread thread = new Thread(() => { Uri uri = new Uri(url); string fileName = System.IO.Path.GetFileName(uri.AbsolutePath); client.DownloadFileAsync(uri, Application.StartupPath + "/" + fileName); }); thread.Start(); } } private void Form1_Load(object sender, EventArgs e) { client = new WebClient(); client.DownloadProgressChanged += Client_DownloadProgressChanged; client.DownloadFileCompleted += Client_DownloadFileCompleted; } private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { MessageBox.Show("Download complete !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { //Update progress bar & label Invoke(new MethodInvoker(delegate () { progressBar.Minimum = 0; double receive = double.Parse(e.BytesReceived.ToString()); double total = double.Parse(e.TotalBytesToReceive.ToString()); double percentage = receive / total * 100; lblStatus.Text = $"Downloaded {string.Format("{0:0.##}", percentage)}%"; progressBar.Value = int.Parse(Math.Truncate(percentage).ToString()); })); } } }
VIDEO TUTORIALS
- How to save files using SaveFileDialog in C#
- How to make an Alarm clock with sound in C#
- How to Display Images in DataGridView in C#
- How to Print DataGridView with Header & Footer with Landscape in C#
- How to Create a custom Progress Bar with Percentage in C#
- How to read an image file in C#
- How to use BackgroundWorker in C#
- How to protect .NET code from reverse engineering
Categories
Popular Posts
Flat Able Admin Dashboard Template
11/18/2024
Regal Admin Dashboard Template
11/18/2024
Plus Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024