ashwnacharya
ashwnacharya

Reputation: 14871

Correct usage of Response.Write() in ASP.NET

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?

Upvotes: 1

Views: 20945

Answers (4)

Uwe Keim
Uwe Keim

Reputation: 40736

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.

Upvotes: 7

gideon
gideon

Reputation: 19465

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);

Upvotes: -2

Madhur Ahuja
Madhur Ahuja

Reputation: 22681

Try using Response.End() instead of Flush and Close

That's what I have been using in the past.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

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();
}

Upvotes: 0

Related Questions