Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Exporting Data as XML in a MemoryStream with Download Prompt

0.00/5 (No votes)
24 Nov 2011CPOL 20.4K  
How to generate XML content on the fly and then store the contents in memory

The below snippet demonstrates how to generate XML content on the fly and then store the contents in memory (MemoryStream). This practice is useful if the output can't be saved on the server and avoids the hassle of dealing with permissions. Instead, the XML is generated in memory and then the user will be automatically prompted to download the XML file to their local resource, similar to what happens when attempting to download a file.

C#
protected bool GenerateExportFile()
{
    try
    {
            //Create Memory Stream to store XML Data
            MemoryStream ms = new MemoryStream();
            //Use a writer to create the XML
            using (XmlWriter writer = XmlWriter.Create(ms))
            {
                writer.WriteStartDocument(); //Header
                writer.WriteComment("Comment goes here");
                {
                    writer.WriteStartElement("Root"); //<Root>
                    {
                            writer.WriteStartElement("Element1"); //<Element1>
                            writer.WriteAttributeString("Attribute1", "AtributeValue");
                            writer.WriteStartElement("Element2");
                            writer.WriteString("Element2Value");
                            writer.WriteEndElement(); //<Element2>
                    }

                    writer.WriteEndElement(); //<Root>
                    //Closed the Root Tag
                }
                writer.WriteEndDocument();
                writer.Close();

                //Convert Memory Stream to Byte Array
                byte[] data = ms.ToArray();

                //The Proposed FileName that will show when the 
                //user is prompted to save the file
                string xmlFileName = "OrdExp_" + DateTime.Today.Year.ToString() + 
                    DateTime.Today.Month.ToString("00") + 
                    DateTime.Today.Day.ToString("00");

                //Creating the Context
                HttpContext.Current.Response.Clear();

                //Heads up browser, here comes some XML
                HttpContext.Current.Response.ContentType = "text/xml";
                HttpContext.Current.Response.AddHeader("Content-Disposition:", 
                    "attachment;filename=" + HttpUtility.UrlEncode(xmlFileName));

                //Set the size of the file so the progress bar reports that correctly
                HttpContext.Current.Response.AddHeader("Content-Length", 
                    data.Length.ToString());

                //Download the file and prompt the user to save
                HttpContext.Current.Response.BinaryWrite(data);
                HttpContext.Current.Response.End();
                ms.Flush();
                ms.Close();
                return true;
            }
    }
    catch (Exception exc)
    {
        lblMsg.Text = "Error Generating File: " + exc.Message;
        return false;
    }            
    return true;   
}//Method

This code was used to generate XML data output and then added the ability to automatically export the data to a local machine.

Hope this helps!
Will

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)