Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing MemoryStream to Response Object

I am using the following code to stream pptx which is in a MemoryStream object but when I open it I get Repair message in PowerPoint, what is the correct way of writing MemoryStream to Response Object?

HttpResponse response = HttpContext.Current.Response; response.Clear(); response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));                 response.BinaryWrite(masterPresentation.ToArray()); response.End(); 
like image 956
Ali Avatar asked Dec 08 '12 15:12

Ali


2 Answers

I had the same problem and the only solution that worked was:

Response.Clear(); Response.ContentType = "Application/msword"; Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx"); Response.BinaryWrite(myMemoryStream.ToArray()); // myMemoryStream.WriteTo(Response.OutputStream); //works too Response.Flush(); Response.Close(); Response.End(); 
like image 78
playful Avatar answered Oct 05 '22 14:10

playful


Assuming you can get a Stream, FileStream or MemoryStream for instance, you can do this:

Stream file = [Some Code that Gets you a stream]; var filename = [The name of the file you want to user to download/see];  if (file != null && file.CanRead) {     context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");     context.Response.ContentType = "application/octet-stream";     context.Response.ClearContent();     file.CopyTo(context.Response.OutputStream); } 

Thats a copy and paste from some of my working code, so the content type might not be what youre looking for, but writing the stream to the response is the trick on the last line.

like image 37
Ian Robertson Avatar answered Oct 05 '22 16:10

Ian Robertson