-2

I have a xml string and need to download the string to a .xml file. I am working on a asp.net web application. Following is my code.

   protected void btnDownloadXML_Click(object sender, EventArgs e)
    {
        try
        {
            string xmltext = divLogResults.InnerText;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmltext);
            doc.Save("myfilename.xml");

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/xml";
            response.AddHeader("Content-Disposition", "attachment; filename=" + doc.Name + ";");
            response.Flush();
            response.End();

        }
        catch(Exception ex)
        {
            throw ex;
        }

    }

But I am only getting an empty xml text on download named #document.xml. What am I doing wrong.

wickjon
  • 900
  • 5
  • 14
  • 40
  • Possible duplicate [How do I write an XML string to a file?](http://stackoverflow.com/questions/590881/how-do-i-write-an-xml-string-to-a-file) – Izzy Nov 19 '14 at 09:58
  • 1
    Looks like you forgot to `TransmitFile()` the file you just created. You could also write the markup directly to the HTTP response, there is no actual need to use a file as an intermediate here. – Frédéric Hamidi Nov 19 '14 at 10:00
  • IMHO it would be better to extract this logic from the aspx file and [create a Handler (ashx)](http://www.intstrings.com/ramivemula/asp-net/how-to-download-files-from-server-to-client-using-a-generic-handler/). – BCdotWEB Nov 19 '14 at 11:09

1 Answers1

1

Think I was confusing the code. The following code did what I wanted.

HttpResponse response = HttpContext.Current.Response;

            string xmlString = divLogResults.InnerText;
            string fileName = "ExportedForm.xml";

            response.StatusCode = 200;

            response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            response.AddHeader("Content-Transfer-Encoding", "binary");
            //response.AddHeader("Content-Length", _Buffer.Length.ToString());

            response.ContentType = "application-download";
            response.Write(xmlString);
wickjon
  • 900
  • 5
  • 14
  • 40