Wednesday, 29 October 2014

How to download files asynchronously using only HTTP

all you need is these 2 simple methods in your class.
private void downloadFile(string fileUrl)
{ 
  HttpWebRequest request;
 
  request = WebRequest.Create(fileUrl) as HttpWebRequest;
  // this reduces connection time considerably but it's not supported in windows phone 8
  request.Proxy = null; 
 
  if(request != null)
  {
    request.BeginGetResponse(downloadFile, request); 
  }
}
 
private void downloadFile(IAsyncResult responseResult)
{   
  HttpWebRequest request = responseResult.AsyncState as HttpWebRequest ;
  if(request != null)
  {
    // the using here is VERY important if you don't want leaks
    using (WebResponse response = request.EndGetResponse(responseResult))
    {
      if(((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
      {
        // if you want to use a dynamic file location, just make the file name a member variable in your class
        using(FileStream fileStream = File.Open(@"c:\files\my_downloaded.file", FileMode.Create))
        {
          Stream source = response.GetResponseStream();
          int bytesRead;
          byte[] streamBuffer = new byte[1024*64];
          while ((bytesRead = source.Read(streamBuffer, 0, streamBuffer.Length)) > 0)
          {
            fileStream.Write(streamBuffer, 0, bytesRead);
          }
        }
      }
    }
  }
}