Asinka

DownloadingFile

Jan 28th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Security;
  5.  
  6.  
  7. class DownloadingFile
  8. {
  9.     static void Main()
  10.     {
  11.         try
  12.         {
  13.             string remoteUri = "http://www.devbg.org/img/";
  14.             string fileName = "Logo-BASD.jpg";
  15.             string outputFile = @"C:\Downloads\Logo-BASD.jpg";
  16.             string WebResource = null;
  17.  
  18.             // Create output directory (if necessary)
  19.             string outputFolder = Path.GetDirectoryName(outputFile);
  20.             if (!Directory.Exists(outputFolder))
  21.             {
  22.                 Directory.CreateDirectory(outputFolder);
  23.             }
  24.  
  25.             WebClient myWebClient = new WebClient();
  26.             // Concatenate the domain with the Web resource filename.
  27.             WebResource = remoteUri + fileName;
  28.             Console.WriteLine("Downloading File \"{0}\" from:\n\"{1}\" .......\n\n", fileName, WebResource);
  29.             // Download the Web resource and save it into the current filesystem folder.
  30.             myWebClient.DownloadFile(WebResource, outputFile);
  31.             Console.WriteLine("Successfully Downloaded File \"{0}\" from:\n\"{1}\"", fileName, WebResource);
  32.             Console.WriteLine("\nDownloaded file saved in the following file system folder:\n" + outputFile);
  33.         }
  34.         catch (ArgumentNullException)
  35.         {
  36.             Console.WriteLine("Address or filename parameter is null!");
  37.         }
  38.         catch (WebException)
  39.         {
  40.             Console.WriteLine("Error, becouse one of the following reason:");
  41.             Console.WriteLine("- The URI formed by combining BaseAddress and address is invalid.");
  42.             Console.WriteLine("- Filename is a null reference, or Empty.");
  43.             Console.WriteLine("- An error occurred while downloading data.");
  44.         }
  45.         catch (NotSupportedException)
  46.         {
  47.             Console.WriteLine("The method has been called simultaneously on multiple threads.");
  48.         }
  49.         catch (SecurityException)
  50.         {
  51.             Console.WriteLine("You don't have permission to write to local file!");
  52.         }
  53.     }
  54. }
Add Comment
Please, Sign In to add comment