Windows Forms: How to Download a File from Internet in C#
By FoxLearn 6/25/2017 8:17:45 PM 14.49K
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 make a Notepad in C#
- How to Receive SMS from WhatsApp in C#
- How to Add Combobox to DataGridView in C#
- How to Create Multiple pages on the Form using Panel control in C#
- How to insert Math Equation to RichTextBox in C#
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
Categories
Popular Posts
How to sign a powershell script
10/03/2024
How to get Credentials in PowerShell?
10/03/2024
How to implement Jint in C#
09/14/2024