Convert XDocument to Stream

mickyjtwin picture mickyjtwin · Apr 15, 2009 · Viewed 41.2k times · Source

How do I convert the XML in an XDocument to a MemoryStream, without saving anything to disk?

Answer

Jon Skeet picture Jon Skeet · Dec 5, 2011

In .NET 4 and later, you can Save it to a MemoryStream:

Stream stream = new MemoryStream();
doc.Save(stream);
// Rewind the stream ready to read from it elsewhere
stream.Position = 0;

In .NET 3.5 and earlier, you would need to create an XmlWriter based on a MemoryStream and save to that, as shown in dtb's answer.