Return download file using stream in asp.net web forms

In asp.net MVC, I can do something like the following that will open the stream:

Stream strm1 = GenerateReport(Id); return File(strm1, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report_" + reportId.ToString() + ".xlsx"); 

Notice how I pass strm1, which is a stream. Then I can call it Report_ + ... xlsx, as shown in the example above.

Is there a similar way to do this using asp.net web forms using C #.

+7
source share
3 answers

You can use TransmitFile or WriteFile if the file is in the folder of your website.

 string fileName = string.Format("Report_{0}.xlsx", reportId); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName)); Response.TransmitFile(fileName); Response.End(); 

Flow

If your data is already in memory, you want this method to write the response in pieces.

 Stream stm1 = GenerateReport(Id); Int16 bufferSize = 1024; byte[] buffer = new byte[bufferSize + 1]; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId)); Response.BufferOutput = false; int count = stm1.Read(buffer, 0, bufferSize); while (count > 0) { Response.OutputStream.Write(buffer, 0, count); count = stm1.Read(buffer, 0, bufferSize); } 
+9
source share

I use this extension to send the stream as a download file:

 public static class ToDownloadExtention { public static void ToDownload(this Stream stream, string fileName, HttpResponse response) { response.Clear(); response.ContentType = "application/octet-stream"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName)); stream.CopyTo(response.OutputStream); response.End(); } } 

And the following is used:

 var stream = new MemoryStream(); stream.ToDownload("someFileName.ext",Response); 
+4
source share

Or, if you have a stream ready for recording, just copy it into the response stream:

 Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Disposition", "attachment; filename={your file name}"); Response.OutputStream.Write(stream, 0, stream.length); Response.End(); 

Added the same code for visibility

0
source share

All Articles