download file C#

download file C#

1. use client

//create Path            
string downloadPath = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Downloads\") + fileName;

        //use WebClient().DownloadFile(string address, string fileName)
        // Summary:
        //     Downloads the resource with the specified URI to a local file.
        //
        // Parameters:
        //   address:
        //     The URI from which to download data.
        //
        //   fileName:
        //     The name of the local file that is to receive the data.
        //
        // Exceptions:
        //   T:System.ArgumentNullException:
        //     The address parameter is null.
        //
        //   T:System.Net.WebException:
        //     The URI formed by combining System.Net.WebClient.BaseAddress and address is invalid.-or-
        //     filename is null or System.String.Empty.-or-The file does not exist.-or- An error
        //     occurred while downloading data.
        //
        //   T:System.NotSupportedException:
        //     The method has been called simultaneously on multiple threads.      
using (var client = new WebClient())
 {
    try
     {
       client.DownloadFile(
       imgUrl,
       downloadPath);
     }
     catch (Exception)
     {
       throw;
      }
}

2. return File

 function downloadImg() {

        var imgUrl = bigImage.src;
        var fileName = bigImgFileName.innerHTML;

        window.location = '../Search/downloadImg?imgUrl=' + imgUrl + '&fileName=' + fileName;

    }

public ActionResult downloadImg(string imgUrl, string fileName)
{
//get .jpg
var fileExt = Path.GetExtension(imgUrl);

//get MIME type  (contentType
var content = MimeMapping.GetMimeMapping(imgUrl);
var client = new WebClient();
Byte[] file = null;
fileName = fileName + fileExt;
try
{
    file = client.DownloadData(imgUrl);

}
catch (Exception)
{
// if the imgUrl doesn't have image
    string filepath = Server.MapPath("~/Content/Images/ImageNotFound.png");
    Stream iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
    return File(iStream, "image/png", fileName);
}
return File(file, content, fileName);

}