XmlReader may or may not be supported by Stream . I tricked myself with some methods, using reflection to try to get a Stream or TextWriter , supporting XmlReader, but in the end, I think that it is probably easiest to write an object to a new stream; I would recommend this method for the accepted answer, because the accepted answer will not work very well on large documents, and this is basically a simplified version of what the BizTalk version in Jay answer will do (BizTalk does some automatic detection of whether it should use FileStream or MemoryStream and has other special processing for XML):
public static class XmlExtensions { public static MemoryStream ToStream(this XmlReader reader) { MemoryStream ms = new MemoryStream(); reader.CopyTo(ms); return ms; } public static FileStream ToStream(this XmlReader reader, string fileName) { FileStream fs = new FileStream(fileName, FileMode.Create); reader.CopyTo(fs); return fs; } public static void CopyTo(this XmlReader reader, Stream s) { XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = false;
CopyTo allows you to customize the stream as you like; ToStream gives you some useful common cases when you just want to quickly get a regular MemoryStream (for small XML files) or use FileStream (for larger ones).
Of course, in the end, if you really do this for serialization purposes, it would be nice to add overloading to your serialization class, for example:
XMySerializer.Deserialize(XmlReader reader, object graph)
Both XmlSerializer and DataContractSerializer in BCL follow this idea ...
source share