Thursday, November 3, 2011

Exporting Data as XML in a MemoryStream with Download Prompt

The below snippet demonstrates how to generate XML content on the fly and then storing 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.

protected bool GenerateExportFile()
            //Create Memory Stream to store XML Data
            MemoryStream ms = new MemoryStream();
            //Use a writer to greate 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.WriteEndElement(); //<Element2>

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

                //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
                //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

                return true;
    catch (Exception exc)
        lblMsg.Text = "Error Generating File: " + exc.Message;
        return false;
    return true;  

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,

No comments:

Post a Comment