Wednesday, January 30, 2013

ASP.Net: Html Text at End of Downloaded File

I am having this issue a few days ago which is quite strange for me since I am new to development in ASP.Net and I have shifted from Windows Application Development in .Net.

Issue:
The issue is when you save a file from any webpage then some html text gets appended with the file which some times makes the file corrupt.

The code which I am using in order to save the file is shown below:

FileStream fStream = new FileStream("C://1.pdf", FileMode.Open, FileAccess.Read);
long FileSize = fStream.Length;

byte[] Buffer = new byte[(int)FileSize];
fStream.Read(Buffer, 0, (int)FileSize);
fStream.Close();

Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=Output.pdf");
Response.BinaryWrite(Buffer);
Response.Flush();

Solution:
The solution is really simple which I got from google search.

The working code is shown below:

FileStream fStream = new FileStream("C://1.pdf", FileMode.Open, FileAccess.Read);
long FileSize = fStream.Length;

byte[] Buffer = new byte[(int)FileSize];
fStream.Read(Buffer, 0, (int)FileSize);
fStream.Close();

Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=Output.pdf");
Response.BinaryWrite(Buffer);
Response.End();

The only issue is with the Response.Flush() line which I use often when working as a Desktop developer. But with web its not the case. So we have to call Response.End() and should not call Response.Flush().

Hope many will get benefit from this.

No comments:

Post a Comment