I am really a newbie with streams, so I don’t really know what I am doing here. 🙂
I have a XElement containing XML. I want it to return it as a file to the user.
XElement xml = IndicesXMLGenerator.XML();
//Code for creating a memorystream for returning to browser as file
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.Unicode);
xml.Save(writer);
writer.Close();
//Code for direct saving to harddisk
FileStream filestream = new FileStream(@"D:\indices.xml", FileMode.Create);
XmlTextWriter writer2 = new XmlTextWriter(filestream, System.Text.Encoding.Unicode);
xml.Save(writer2);
writer2.Close();
filestream.Close();
//Return memorystream as fileresult
return base.File(new MemoryStream(stream.GetBuffer()), "text/xml", "AlleIndices.xml");
}
When I open the file that I got from my browser, it is totally mangled.
like: �< ? X M L
When I change the encoding in the code to UTF8 it gives me a normal looking document, but at the end I get a lot of 0x0 characters that make the document invalid.
Strange thing is that the XML file that I saved directly to the harddisk from within the code is:
- Perfectly fine in it’s encoding
- Doesn’t contain any strange
0x0characters
So, what’s going on here? Why can’t I easily stream my XElement to the browser as file?
Calling
GetBufferwill return the stream’s internal buffer, which will be larger than the actual data. (In case you write some more to the stream)You need to replace the call to
GetBufferwithToArray(), which will copy the used portion of the buffer to a new array.However, the best way to do this is return the original MemoryStream, but first set the
Positionproperty to 0, like this: