Question

I'm trying to write an XML file to the response when a button is clicked so the user can download the file. This works fine with an Excel file, but when I use the "text/xml" content type the file contains the expected contents, but with the webpage HTML appended to the end.

I assume since the button click is returning the page HTML it is merged with the file. I tried using Response.ClearContent() to try and clear the response, but it didn't work.

protected void Button1_Click(object sender, EventArgs e) {
    string fileName = "myFile.xml";
    string filePath = Server.MapPath("~/temp/myFile.xml");
    Response.ContentType = "text/xml";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.ClearContent(); //I assumed this would clear the HTML before the file is written.
    Response.WriteFile(filePath);
    Response.Flush();
    File.Delete(filePath);
    Context.ApplicationInstance.CompleteRequest();
}

How do I make sure the page is not written to the XML file?

Était-ce utile?

La solution

The HTML is being rendered after the button's Click event is raised, so clearing the content at that point won't have any effect.

Try adding Response.End(); to the end of your method.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top