I'm trying to write a small piece of XML to a memory stream, then read the written content from the memory stream and save it to a variable.
I have the following logic that works for writing and reading simple text value:
string text = null;
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream))
{
streamWriter.Write("Foo!");
streamWriter.Flush();
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream))
{
text = streamReader.ReadToEnd();
}
}
}
await context.Response.WriteAsync(text, Encoding.UTF8);
But replacing the StreamWriter
with XmlWriter
and trying to write actual XML results in ObjectDisposedException
.
string text = null;
using (var memoryStream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(memoryStream))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Foo");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream))
{
text = streamReader.ReadToEnd();
}
}
}
System.ObjectDisposedException: Cannot access a closed Stream.
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlUtf8RawTextWriter.FlushBuffer()
at System.Xml.XmlUtf8RawTextWriter.Flush()
at System.Xml.XmlWellFormedWriter.Close()
at System.Xml.XmlWriter.Dispose(Boolean disposing)
at System.Xml.XmlWriter.Dispose()
But if I remove the using
block around XmlWriter
... it works.
string text = null;
using (var memoryStream = new MemoryStream())
{
var xmlWriter = XmlWriter.Create(memoryStream));
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Foo");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream))
{
text = streamReader.ReadToEnd();
}
}
await context.Response.WriteAsync(text, Encoding.UTF8);
I cannot get it around my head why that happens and why I cannot use the using
block around TextWriter
. Same steps done with StreamWriter
works just fine, so what's the difference with XmlWriter
? I assume that stream will not be closed until the end of using block is reached. Where is the flaw in my way of thinking?