2

I want to export some data from my ASP.NET web form application to a downloadable XML file but I can't get it to display the downlaoded information as an XML file. It outputs the information as an html document instead of XML.

protected void ExportXMLButton_Click(object sender, EventArgs e)
{

    using (MemoryStream stream = new MemoryStream())
    {
        // Create an XML document. Write our specific values into the document.
        XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);
        // Write the XML document header.
        xmlWriter.WriteStartDocument();
        // Write our first XML header.
        xmlWriter.WriteStartElement("WebApplications");
        // Write an element representing a single web application object.
        xmlWriter.WriteStartElement("WebApplication");
        // Write child element data for our web application object.
        xmlWriter.WriteElementString("Date", DateTime.Now.ToString());
        xmlWriter.WriteElementString("Programmer", "Label1.Text");
        xmlWriter.WriteElementString("Name", "Sample name ");
        xmlWriter.WriteElementString("Language", "C# ");
        xmlWriter.WriteElementString("Status", "Done");
        // End the element WebApplication
        xmlWriter.WriteEndElement();
        // End the document WebApplications
        xmlWriter.WriteEndElement();
        // Finilize the XML document by writing any required closing tag.
        xmlWriter.WriteEndDocument();
        // To be safe, flush the document to the memory stream.
        xmlWriter.Flush();
        // Convert the memory stream to an array of bytes.
        byte[] byteArray = stream.ToArray();
        // Send the XML file to the web browser for download.
        Response.Clear();
        Response.AppendHeader("Content-Disposition", "filename=MyExportedFile.xml");
        Response.AppendHeader("Content-Length", byteArray.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(byteArray);
        xmlWriter.Close();

    }
}

I expect the output to be an XML file, but the actual output is my data being shown on the screen as a text.

Obi Wan
  • 21
  • 2
  • 1
    Xml is Text!!!! – jdweng Aug 28 '19 at 15:58
  • 3
    This may depend on how the browser handles XML documents. Eg, on my development machine, firefox is set to download XML files, and Chrome is set to display them in the browser. – Kami Aug 28 '19 at 15:58

2 Answers2

1

You're writing the wrong headers. Use:

Content-Disposition: attachment;filename=...
Content-Type: application/xml

As a minimum. See:

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

I think that deleting this is the answer:

Response.AppendHeader("Content-Length", byteArray.Length.ToString());
thatguy
  • 21,059
  • 6
  • 30
  • 40
phong
  • 1