How to synchronously download a file from a URL in C#

The WebClient class in the System.Net namespace provides the DownloadFile() method to download a resource (or file) onto the disk. This method takes the URL of the resource and the path of the output file as input, and synchronously downloads and writes the file to the output file.

Syntax

This method has two overloads.

public void DownloadFile (Uri address, string fileName);

public void DownloadFile (string address, string fileName);

The DownloadFile() method throws exceptions in the following scenarios:

  • If the input URL or output file path is null.
  • If the input URL is invalid or the output file is empty.
  • If there is an error in downloading the file.

Code

In the example below, we are downloading an image file and saving it in the current working directory with the name image.png.

The file download operation is a blocking operation.

Once the file is successfully downloaded, we validate if the downloaded file exists. Then, the program will print the message below and terminate.

File Downloaded Successfully
using System;
using System.Net;
using System.IO;
class FileDownloader
{
static void Main()
{
string path = "http://www.educative.io/cdn-cgi/image/f=auto,fit=contain,w=2400/api/edpresso/shot/5224207262154752/image/5022165490991104.png";
using(WebClient client = new WebClient())
{
client.DownloadFile(path,"image.png");
}
if(File.Exists("image.png"))
{
Console.WriteLine("File Downloaded Successfully");
}
else
{
Console.WriteLine("Not able to download the file.");
}
}
}

To download an HTTP resource, the GET method is used. To download an FTP resource, and the RETR command is used.