I am trying to force a download of an XML file when the user visits a page.
This is the code I am using
public partial class GenerateTemplate : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
//.............
//Going about generating my XML
//.............
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=template.xml");
Response.Write(xmlDoc.InnerXml);
Response.Flush();
Response.Close();
}
}
I am facing a problem that my download window hangs indefinitely, without ever completing the download/Open of the file.
What am I doing wrong? Am I not disposing any objects or closing any connections here?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I’ve posted a reply to a similar question. To quote myself:
Just a small addition to the other answers. At the very end of a download I execute:
context.Response.Flush(); context.ApplicationInstance.CompleteRequest();
I learned that otherwise, the download sometimes does not complete successfully.
This Google Groups posting also notes that Response.End throws a ThreadAbortException which you could avoid by using the CompleteRequest method.
Method 2
Try using Response.End() instead of Flush and Close
That’s what I have been using in the past.
Method 3
Have you tried setting the content type and calling Response.End():
protected void Page_Load(object sender, EventArgs e)
{
//.............
//Going about generating my XML
//.............
Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=template.xml");
Response.Write(xmlDoc.InnerXml);
Response.End();
}
Method 4
You say you want to have a file download With asp.net web forms you would do this:
context.Response.ContentType = //MIME type
// Set the filename
context.Response.AddHeader("content-disposition", "attachment;filename=" + queryFile);
// Stream the file to the client
context.Response.WriteFile(file);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0