Download File from Internet Synchronously and Asynchronously



This program will let you download a file both ways i.e. Synchronously and Asynchronously. Just feed the file URL into the first text-box and the save file location into the second text-box  Then simply choose from the two options to download the file from the internet. 


There is also a progress indicator that shows the download progress. See code below:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Download_File_from_Internet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnPaste_Click(object sender, EventArgs e)
        {
            txtPaste.Text =  Clipboard.GetText();
        }

        private void btnLocation_Click(object sender, EventArgs e)
        {
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName != "")
            {
                txtLocation.Text = saveFileDialog.FileName;
            }
        } 
        
        private void btnSyncDwnld_Click(object sender, EventArgs e)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFile(txtPaste.Text, txtLocation.Text);
            //webClient.Dispose();
        }

        private void btnAsyncDwnld_Click(object sender, EventArgs e)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFileCompleted += Download_Completed;
            webClient.DownloadProgressChanged += Download_ProgressChanged;
            webClient.DownloadFileAsync(new Uri(txtPaste.Text), txtLocation.Text);
            //webClient.Dispose();
        }

        private void Download_ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void Download_Completed(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Download completed!");
        }
    }
}


Custom Search