Windows Forms: How to Download a File from Internet in C#

How to Download a File from Internet with the Progress Bar in C# using webclient

Step 1Click 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

c# download fileStep 2: Design your form as below

download file in c#

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