Reputation: 5042
I'm pushing a PEM file towards my website user for download. here is the code:
try
{
FileStream sourceFile = null;
Response.ContentType = "application/text";
Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(RequestFilePath));
sourceFile = new FileStream(RequestFilePath, FileMode.Open);
long FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
catch (Exception exp)
{
throw new Exception("File save error! Message:<br />" + exp.Message, exp);
}
The issue is that the file that is downloaded has the content that should be there + a copy of the whole web page's HTML too.
Whats happening here?
Upvotes: 1
Views: 1923
Reputation: 32602
I agree with @Amiram Korach's solution.
That is add Response.ClearContent();
before Response.ContentType...
But as per your comment
Still the whole page get written
@Amiram Korach replied to add Response.End()
at the end.
But it throws System.Threading.ThreadAbortException
.
So I advice you to add additional catch
to catch System.Threading.ThreadAbortException
and don't put error message in Response.Write
otherwise it will also be added to your text file:
try
{
FileStream sourceFile = null;
Response.ClearContent(); // <<<---- Add this before `ContentType`.
Response.ContentType = "application/text";
.
.
Response.BinaryWrite(getContent);
Response.End(); // <<<---- Add this at the end.
}
catch (System.Threading.ThreadAbortException) //<<-- Add this catch.
{
//Don't add anything here.
//because if you write here in Response.Write,
//that text also will be added to your text file.
}
catch (Exception exp)
{
throw new Exception("File save error! Message:<br />" + exp.Message, exp);
}
This will solve your problem.
Upvotes: 0
Reputation: 19953
Place the following...
Response.Clear();
Before...
Response.ContentType = "application/text";
Update
As @Amiram says in his comments (and I was about to add myself anyway)...
After...
Response.BinaryWrite(getContent);
Add...
Response.End();
Upvotes: 5
Reputation: 13286
Add this line:
Response.ClearContent();
Response.ContentType = "application/text";
...
Upvotes: 3