Search code examples
c#.nethttpwebrequest

File download For Current Request


I need to download the file as http response for the current http request.

Until now I used code as

System.Uri uri = System.Web.HttpContext.Current.Request.Url;   

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(
    Path.Combine(uri.ToString(), filename));

httpRequest.Method = "GET";

using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{                 
     using (Stream responseStream = httpResponse.GetResponseStream())
     {
         using (FileStream localFileStream = new FileStream(
             Path.Combine(localFolder, filename), FileMode.Open))
         {                  
             int bytesRead;

             while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
             {
                 totalBytesRead += bytesRead;    
                 localFileStream.Write(buffer, 0, bytesRead);
             }
         }
     }
}

But this code the request is only sending but not getting any responses...

Is this possible?


Solution

  • You should get the file off disk then use the Response.OutputStream to write the file directly to the response. Make sure to set the correct content headers so the browser will know what is coming.

    FileInfo file = new FileInfo(Path.Combine(localFolder, filename));
    int len = (int)file.Length, bytes;
    Response.ContentType = "text/plain"; //Set the file type here
    Response.AddHeader "Content-Disposition", "attachment;filename=" + filename; 
    context.Response.AppendHeader("content-length", len.ToString());
    byte[] buffer = new byte[1024];
    
    using(Stream stream = File.OpenRead(path)) {
        while (len > 0 && (bytes =
            stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            Response.OutputStream.Write(buffer, 0, bytes);
            len -= bytes;
        }
    }