I have the following code
public void SerializeToStream(Stream stream)
{
var xml = // Linq to xml code here
// Write to the stream
var writer = new StreamWriter(stream);
writer.Write(xml.ToString());
}
My xml object has the correct data, and I have verified that xml.ToString() shows everything correctly, but after writer.Write(xml.ToString()) is called my incoming stream (regardless if it’s a FileStream or MemoryStream still has nothing in it (and a length of zero). No exceptions are thrown. Why is this happening?
As a note, I cannot use xml.WriteTo() because the XmlWriter class adds extra stuff (the <xml> declaration tag) which I cannot have in my xml (Company policy for integration with another system I do not have control over).
You’re never flushing or closing the writer. (I’d normally suggest closing the writer, but that will also close the stream, which may not be what you want.) Simply add:
at the end of the method.
Note that you can remove the XML declaration from an
XDocument, if you want. For example:That should make it simpler: