Download A File Using The WebClient Class In C#

This snippet downloads a file using the WebClient Class from a website.


  1. using System;
  2. using System.Net;
  3. class Program
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         string host ="http://www.yourdomain.com/file.zip";
  8.         string savelocation = Environment.CurrentDirectory + "\\" + host.Substring(host.LastIndexOf("/") + 1);
  9.         try
  10.         {
  11.             WebClient wClient = new WebClient();
  12.             wClient.DownloadFile(host, savelocation);
  13.             Console.WriteLine("File has been downloaded to " + savelocation);
  14.         }
  15.         catch (WebException e)
  16.         {
  17.             Console.WriteLine(e.Message);
  18.         }
  19.         Console.ReadKey();
  20.     }
  21. }

No comments:

Post a Comment