Search code examples
c#.netdownloadxmldocumentmemorystream

XmlDocument downloads with incorrect extension even with Content-Disposition Set


I am using what seems to be a pretty standard way of downloading an XmlDocument to the browser using a memory stream:

// Create document and root node
var dashboardXmlDoc = GetXml();

// Download the file
using (MemoryStream xmlMemoryStream = new MemoryStream())
{
    using (XmlWriter writer = XmlWriter.Create(xmlMemoryStream))
    {
        writer.Flush();
        dashboardXmlDoc.WriteTo(writer); // Write to memorystream
    }

    byte[] data = xmlMemoryStream.ToArray();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition:", "filename=samplefile.xml");
    HttpContext.Current.Response.AppendHeader("Content-Length", data.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";

    HttpContext.Current.Response.BinaryWrite(data);
    HttpContext.Current.Response.End();
}

All seems to work fine, except that the file does not have the specified name or extension...it comes out named after the .apsx page corresponding to the .apsx.cs in which this code runs.

Very similar in some respects to this case:

Change name of file sent to client?

Though I am using a memory stream and dealing with XML, and already have the Content-Disposition set so the given fix will not work here (unless I have somehow done that incorrectly?)

I have been able to get the XML Document to open in the browser, but am thinking it must be possible to get the proper filename and extension here.

I have tried changing the ContentType to "text/xml", and have tried with and without "attachment;" before the filename parameter of the Content-Disposition header.

Please let me know if I can provide any more code or check anything!


Solution

  • In order to solve the problem, I'd propose the following steps (those worked for me):

    • Remove the colon : in the Content-Disposition header name.
    • Use attachment in the Content-Disposition header value.
    • Change the content type to text/xml.

    Sample:

    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=samplefile.xml");
    // ...
    HttpContext.Current.Response.ContentType = "text/xml";