The PDF content is buffered in memory, and doesn't get flushed to the underlying stream until the buffer is full, or the
Close
method is called.
Move the
pdfDoc.Close();
line above the code that saves the file:
pdfDoc.Close();
using (var fileStream = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew, FileAccess.Write))
{
memStream.Seek(0, SeekOrigin.Begin);
memStream.CopyTo(fileStream);
}
NB: This is an ASP.NET application. You
cannot use
MessageBox.Show
to show messages to the user.
It might
appear to work when you debug the code in Visual Studio. But that's only because, in the specific case, the server and the client are the same machine.
As soon as you deploy your code to a real server, the code will stop working. In the best case,
MessageBox.Show
will throw an exception telling you that it cannot be used in a non-interactive process. In the worst case, the message will appear
on the server, where nobody will ever see it, and your code will hang waiting for someone to log in to the server and acknowledge thousands of messages.
NB2: MemoryStream.GetBuffer()[
^] returns the raw buffer, which will contain unused bytes. Do not use it to copy the memory stream content to the response, otherwise you will end up with a corrupt file.
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
memStream.Seek(0, SeekOrigin.Begin);
memStream.CopyTo(Response.OutputStream);