I thought MVC was supposed to make all this easier but I'm trying various ways and getting issues.
If I try the accepted answer for this question (changing the content type accordingly)... How to cr开发者_运维知识库eate file and return it via FileResult in ASP.NET MVC?
...I get into trouble because my encoding in the xml file is UTF-16.
The error I get is:
Switch from current encoding to specified encoding not supported.
This suggests that somewhere I need to tell MVC that I want UTF-16. Alternatively I want a different method that uses binary and not text.
This is what I've settled for:
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 perfect and I could probably just use a FileContentResult and not bother with the memory stream. Also, I don't think IE likes the unicode. It complains that "A name was started with an invalid character" despite the xml being fine and happily opening in firefox.
However it seems to do the job.
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 calling Flush and setting Position are mandatory things to do.
Saving to stream works better than initializing through OuterXml: 1) less frictions, 2) resulting XML is formatted instead of being one-line string.
精彩评论