How to pass XML document in memory as attachment to asp.net mvc site

I thought MVC was supposed to make the whole thing easier, but I am trying in different ways and getting problems.

If I try the accepted answer to this question (changing the content type accordingly) ... How do I create a file and return it via FileResult in ASP.NET MVC?

... I'm having trouble because my encoding in the XML file is UTF-16.

The error I am getting:

Jumping from the current encoding to the specified encoding is not supported.

This suggests that somewhere I need to tell MVC that I want UTF-16. Alternatively, I want to use a different method that uses binary and not text.

+2


a source to share


2 answers


Here's what I solved:

public FileStreamResult DownloadXML()
{
    string name = "file.xml";
    XmlDocument doc = getMyXML();
    System.Text.Encoding enc = System.Text.Encoding.Unicode;
    MemoryStream str = new MemoryStream(enc.GetBytes(doc.OuterXml));

    return File(str, "text/xml", name);
}

      



I don't think this is ideal and I could just use FileContentResult and not worry about memory flow. Also, I don't think IE likes unicode. He complains that "The name was started with an invalid character" even though the xml was fine and happily opened in firefox.

However, it seems to do the job.

+3


a source


    public FileStreamResult DownloadXML()
    {
        string name = "file.xml";
        XmlDocument doc = getMyXML();
        var str = new MemoryStream();
        doc.Save(str);
        str.Flush();
        str.Position = 0;

        return File(str, "text/xml", name);
    }

      

Note that the Flush call and the Position setting are required.



Saving to a stream works better than initializing via OuterXml: 1) less friction, 2) the resulting XML is formatted instead of a one-line string.

+2


a source







All Articles