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.
protected bool GenerateExportFile()
{
try
{
MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms))
{
writer.WriteStartDocument();
writer.WriteComment("Comment goes here");
{
writer.WriteStartElement("Root");
{
writer.WriteStartElement("Element1");
writer.WriteAttributeString("Attribute1", "AtributeValue");
writer.WriteStartElement("Element2");
writer.WriteString("Element2Value");
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndDocument();
writer.Close();
byte[] data = ms.ToArray();
string xmlFileName = "OrdExp_" + DateTime.Today.Year.ToString() +
DateTime.Today.Month.ToString("00") +
DateTime.Today.Day.ToString("00");
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:",
"attachment;filename=" + HttpUtility.UrlEncode(xmlFileName));
HttpContext.Current.Response.AddHeader("Content-Length",
data.Length.ToString());
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;
}
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