sylviapsh

Download File From the Internet

Jan 27th, 2013
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.IO;
  4.  
  5. class DownloadFileFromInternet
  6. {
  7.   //Write a program that downloads a file from Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and stores it the current directory. Find in Google how to download files in C#. Be sure to catch all exceptions and to free any used resources in the finally block.
  8.  
  9.   static void Main()
  10.   {
  11.     Console.WriteLine("Enter the full download url: "); //Ask for the url of the file to download
  12.     string url = Console.ReadLine(); //Store it in the url string
  13.     string fileName = Path.GetFileName(url); //extract the file name
  14.  
  15.     using (WebClient client = new WebClient())//Open a web client
  16.     {
  17.       try
  18.       {
  19.         client.DownloadFile(url, fileName);//Use the web client with our url and file name
  20.       }
  21.       catch (ArgumentNullException)
  22.       {
  23.         Console.WriteLine("Please provide a url address!"); ;
  24.       }
  25.       catch (WebException)
  26.       {
  27.         Console.WriteLine("An error occurred while trying to download the file! Make sure the url is valid, the file you want to download exists and the internet connection is running!");
  28.       }
  29.       catch (NotSupportedException)
  30.       {
  31.         Console.WriteLine("The DownloadFile method cannot be called simultaneously on multiple threads.");
  32.       }
  33.       finally
  34.       {
  35.         Console.WriteLine("Good bye!");
  36.       }
  37.     }
  38.   }
  39. }
Add Comment
Please, Sign In to add comment