I'm having some problems dealing with downloading a file from the server.
The problem is that the end of the downloaded file is missing.
I have found some indications of other people having similar problems, but nothing that helps me in my problem.
When debugging I have learned that the length of fileData
is correct, and all data is present in the byte array when calling BinaryWrite
.
That leaves the BinaryWrite
, Flush
or Close
calls...
I have read about not using Response.End
or Response.Close
, for example here:
HttpResponse.End vs HttpResponse.Close vs HttpResponse.SuppressContent and it seems like a probable cause, but what should I use instead (have tried to remove Response.Close
completely, but that result in too much data output)?
Someone knows what might cause this behaviour, and how to fix it?
EDIT: Just tried with Response.ContentType = "binary/octet-stream";
and it works like a charm!
What is the difference between text/plain and binary/octet-stream that may cause a behavior like this?
It even works without the Close
call...
MORE EDIT: Seems like compression of Responses was activated on the server-side. Apparently there seems to be an issue with plain text streams when compression is active.
The code I have is:
private void DownloadFile(byte[] fileData, string fileName, string fileExtension)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + fileExtension);
Response.AddHeader("Content-Length", fileData.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "text/plain";
Response.BinaryWrite(fileData);
Response.Flush();
Response.Close();
}