Windows Forms: How to download file from URL in C#

This post shows you How to download file from URL using AltoHttp in C# Windows Forms Application.

Dragging TextBox, Label, Button, ProgressBar controls from the Visual Studio toolbox into your form designer, then design a simple UI allows you to dowload file from url support Pause and Resume in c# as shown below.

C# download file from server

download file from url c# without webclient

Download file from url c# without webclient

Next, You need to dowload and install AltoHttp library from the Manage Nuget Packages.

alohttp c#

AltoHttp is a free library provides fast and easy download management. Using AltoHttp you can easily download file from server without webclient. Moreover, you can easily add the ability to pause and resume in your downloader in c#.

Adding a click event handler to the Start button allows you to download file from the web server.

private void btnStart_Click(object sender, EventArgs e)
    httpDownloader = new HttpDownloader(txtUrl.Text, $"{Application.StartupPath}\\{Path.GetFileName(txtUrl.Text)}");
    httpDownloader.DownloadCompleted += HttpDownloader_DownloadCompleted;
    httpDownloader.ProgressChanged += HttpDownloader_ProgressChanged;

By default, We will store download file from url to folder c#, you can find file download in the debug directory.

And don't forget to declare

private HttpDownloader httpDownloader = null;

C# download file with progress

Adding a ProgressChanged event handler allows you to process download file.

private void HttpDownloader_ProgressChanged(object sender, AltoHttp.ProgressChangedEventArgs e)
    progressBar.Value = (int)e.Progress;
    lblPercent.Text = $"{e.Progress.ToString("0.00")} % ";
    lblSpeed.Text = string.Format("{0} MB/s", (e.SpeedInBytes / 1024d / 1024d).ToString("0.00"));
    lblSize.Text = string.Format("{0} MB", (httpDownloader.TotalBytesReceived / 1024d / 1024d).ToString("0.00"));
    lblStatus.Text = "Downloading...";

Adding a DownloadCompleted event handler allows you to update status when the download completes.

private void HttpDownloader_DownloadCompleted(object sender, EventArgs e)
        lblStatus.Text = "Finished";
        lblPercent.Text = "100%";

You can use this.Invoke((MethodInvoker)delegate{...}) to update control from another thread.

methodinvoker c#

If not, you will get the Cross-thread operation not valid error.

Adding a click event handler to the Pause button allows you to pause downloads.

private void btnPause_Click(object sender, EventArgs e)

How to resume download file in c#

Finally, Add a click event handler to the Resume button allows you to resume download the file.

private void btnResume_Click(object sender, EventArgs e)

Using AltoHttp you can easily pause or resume download file in c#.