14

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

 Stream strm1 = GenerateReport(Id);

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

Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.

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

Nate Pet
  • 44,246
  • 124
  • 269
  • 414

3 Answers3

23

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

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();

Stream

If your data is already in Memory, you want this method which writes the response in chunks.

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);
}
Win
  • 61,100
  • 13
  • 102
  • 181
12

I use this extension to send a stream as a downloadable 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 usage is:

var stream = new MemoryStream();

stream.ToDownload("someFileName.ext",Response);
Zar Shardan
  • 5,675
  • 2
  • 39
  • 37
2

Or if you have a stream ready to be written, simply copy it to 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 same code just for visibility

Zanuff
  • 208
  • 1
  • 8