Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a downloadable file using a stream in asp.net web forms

Tags:

asp.net

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#.

like image 395
Nate Pet Avatar asked Jan 15 '15 22:01

Nate Pet


1 Answers

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);
like image 87
Zar Shardan Avatar answered Sep 27 '22 23:09

Zar Shardan