R – On forcing download: File Download dialog opens twice in IE6 SP1

asp.netdownloadinternet-explorer-6

My ASP.Net page is supposed to create a document and force its download (open a "File Download" dialog). It works fine on most browsers but for some reason, on IE6 SP1 (windows 2000) the "File Download" dialog opens twice.
Any ideas why?

My very simple code (C#):

protected void bnCreateDocument_Click(object sender, EventArgs e)
{

    string documentText = GetDocumentText();


    Response.Clear();
    Response.Charset = "";
    Response.ContentType = "application/msword";

    string filename = "MyDoc.doc";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);

    Response.Write(documentText);
    Response.End();
    Response.Flush();
}

Best Answer

Your code looks fine but there are a couple of odd things about it that I thought I'd point out.

If you're just fetching a file from the filesystem into that string, why not use Response.WriteFile() directly?

Also, Response.End() automatically calls Flush() if buffering is on, so you shouldn't be calling Flush() at the end like that - at best, it should be before the call to End. End() also raises a ThreadAbortedException, so if you can avoid calling it altogether, that would be ideal. If you can use HttpApplication.CompleteRequest(), that's a better approach.

There are some very tricky and obscure bugs to deal with when shutting down the Response object. If after dealing with the Flush and End calls it's still happening, I would examine what's going on with Fiddler, and perhaps try moving this code into an .ashx handler to get it out of the page lifecycle.