The StreamWriter.Close() says it also closes the underlying stream of the StreamWriter. What about StreamWriter.Dispose ? Does Dispose also dispose and/or close the underlyi
The answer is simple, and provided above: yes, disposing a stream closes any underlying stream. Here is an example:
public static string PrettyPrintXML_bug(XDocument document)
{
string Result = "";
using (MemoryStream mStream = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode))
{
writer.Formatting = Formatting.Indented; // <<--- this does the trick
// Write the XML into a formatting XmlTextWriter
document.WriteTo(writer);
// change the memory stream from write to read
writer.Flush();
mStream.Flush();
} // <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- this also "closes" mStream
mStream.Position = 0;//rewind <-- <-- <-- "cannot Read/Write/Seek"
// Read MemoryStream contents into a StreamReader.
using (StreamReader sReader = new StreamReader(mStream)) // <-- <-- Exception: Cannot access a closed stream
{
// Extract the text from the StreamReader.
Result = sReader.ReadToEnd();
}
}
return Result;
}
and here the solution, where you have to delay Dispose to where the underlying MemoryStream is not needed anymore:
public static string PrettyPrintXML(XDocument document)
{
string Result = "";
using (MemoryStream mStream = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode))
{
writer.Formatting = Formatting.Indented; // <<--- this does the trick
// Write the XML into a formatting XmlTextWriter
document.WriteTo(writer);
// change the memory stream from write to read
writer.Flush();
writer.Close();
mStream.Flush();
mStream.Position = 0;//rewind
// Read MemoryStream contents into a StreamReader.
using (StreamReader sReader = new StreamReader(mStream))
{
// Extract the text from the StreamReader.
Result = sReader.ReadToEnd();
}
}// <-- here the writer may be Disposed
}
return Result;
}
Looking at these examples, I do not understand why closing the underlying stream is a feature.
I just liked to share this.