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

CsharpServer Side ProgrammingProgramming

A file can be downloaded from a URL using web client. It is available in System.Net namespace.

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

The web client can be said as an application or web browser (like Google Chrome, Internet Explorer, Opera, Firefox, Safari) which is installed in a computer and used to interact with Web servers upon user’s request. It is basically a consumer application which collects processed data from servers.

A Client and a Server are two parts of a connection, these are two distinct machines, web client requests information, and the web server is basically a PC that is designed to accept requests from remote computers and send on the information requested. Web server is responsible for storing the information in order to be viewed by the clients and is also usually a Web Host. A Web host allows connections to the server to view said stored info.

The WebClient class in C# uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered

with the WebRequest.RegisterPrefix method. The DownloadFile is used to download a file.

WebClient Client = new WebClient ();
client.DownloadFile("url","path");

Example

Say we want to download an image from the path "https://downloadfreeimages.jpg" and save it the computer local directory, below is the code.

using System;
using System.Net;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string url = "https://downloadfreeimages.jpg";
         string savePath = @"D:\Demo\FreeImages.jpg";
         WebClient client = new WebClient();
         client.DownloadFile(url, savePath);
         Console.ReadLine();
      }
   }
}

Output

The above example will download the image from the URL provided and saves it to the given path.

D:\Demo
raja
Published on 19-Aug-2020 11:36:36
Advertisements