[c#] 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();

This question is related to c# asp.net httpresponse

The answer is


I tried all variants of end, close, flush, and System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() and none of them worked.

Then I added the content length to the header: Response.AddHeader("Content-Length", asset.File_Size.ToString());

In this example asset is a class that has a Int32 called File_Size

This worked for me and nothing else did.


Instead of creating the PowerPoint presentation in a MemoryStream write it directly to the Response.OutputStream. This way you don't need to be wasting any memory on the sever as the component will be directly streaming the output to the network socket stream. So instead of passing a MemoryStream to the function that is generating this presentation simply pass the Response.OutputStream.


The problem for me was that my stream was not set to the origin before download.

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);

myMemoryStream.WriteTo(Response.OutputStream); 
Response.Flush();
Response.Close();

Try with this

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.Flush();                
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();

I had the same issue. try this: copy to MemoryStream -> delete file -> download.

string absolutePath = "~/your path";
try {
    //copy to MemoryStream
    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
    { 
        fs.CopyTo(ms); 
    }

    //Delete file
    if(File.Exists(Server.MapPath(absolutePath)))
       File.Delete(Server.MapPath(absolutePath))

    //Download file
    Response.Clear()
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
    Response.BinaryWrite(ms.ToArray())
}
catch {}

Response.End();

First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to httpresponse

Return content with IHttpActionResult for non-OK response Why should I use IHttpActionResult instead of HttpResponseMessage? download csv file from web api in angular js Proper way to return JSON using node or Express Writing MemoryStream to Response Object Returning http status code from Web Api controller Difference between Pragma and Cache-Control headers? How to Use Content-disposition for force a file to download to the hard drive? Return HTTP status code 201 in flask How to get HTTP Response Code using Selenium WebDriver