That's some very confused code: you have a byte array, so you copy it to a
MemoryStream
, then copy the
MemoryStream
to another byte array, and then write that third copy of the data to a local file, before sending the local file back to the client.
You could simply write the original byte array to the file before sending it:
string path = Server.MapPath("~/TestForm.pdf");
File.WriteAllBytes(path, pdfFile);
However, remember that multiple users could be accessing your site at the same time. If two users request a PDF download at the same time, you will be overwriting the file for one user with the data for another. This could lead to corrupted downloads, or to your site exposing confidential information to unauthorized users.
A better solution would be to simply write the byte array directly to the response, bypassing the file system.
response.Clear();
response.ContentType = "application/pdf";
response.AppendHeader("Content-Disposition", "attachment; filename=\"MyFile.pdf\"");
response.OutputStream.Write(pdfFile);
response.End();