Source

BlueGo / BlueGo / DownloadHelper.cs

Full commit
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace BlueGo
{
    class DownloadHelper
    {
        /// <summary>
        /// Function to download a file from URL and save it to local drive
        /// </summary>
        /// <param name="_URL">URL address to download file</param>
        static public void DownloadFileFromURL(string _URL, string _SaveAs)
        {
            try
            {
                if(!RemoteFileExists(_URL))
                {
                    throw new Exception("Url " + _URL + " is not valid.");
                }

                System.Net.WebClient _WebClient = new System.Net.WebClient();
                // Downloads the resource with the specified URI to a local file.
                _WebClient.DownloadFile(_URL, _SaveAs);
            }
            catch (Exception exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", exception.ToString());

                throw new Exception("Download failed." + exception.ToString());
            }
        }

        ///
        /// Checks the file exists or not.
        ///
        /// The URL of the remote file.
        /// True : If the file exits, False if file not exists
        static public bool RemoteFileExists(string url)
        {
            try
            {
                //Creating the HttpWebRequest
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //Setting the Request method HEAD, you can also use GET too.
                request.Method = "HEAD";
                //Getting the Web Response.
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                response.Close();

                //Returns TURE if the Status code == 200
                return (response.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                //Any exception will returns false.
                return false;
            }
        }
    }
}