If I have the following code:
FileStream fs = new FileStream(...);
TextWriter tw = new StreamWriter(fs);
Am I supposed to call only tw.Close(), or fs.Close() as well? I’m using the TextWriter persistently throughout an application, so I can’t just wrap it in a Using(…) block, since I need to be able to use it at multiple points.
Otherwise, I would just write it as:
using (FileStream fs = new FileStream(...))
{
using (TextWriter tw = new StreamWriter(fs))
{
// do stuff
}
}
And avoid the issue at all together. But, I don’t really know what to do in this circumstance. Do I close tw, fs, or both?
Also, more generally: If I compose multiple streams together, such as C(B(A)), can I call Close / Dispose on C and then not worry about having to call it on B and A?
You only need to close the
StreamWriter.From the documentation of the
StreamWriter.Closemethod:Also notable in the documentation of the method:
This means that closing and disposing the
StreamWriterare equivalent. You don’t have to dispose the object after closing it, or close it before disposing it. TheFileStream.Closemethod does the same, so closing or disposing theStreamWriterwill also dispose the stream.If you wouldn’t be able to find information like this for a class, you can always dispose both the writer and the stream to be safe. Disposing an object that has already been disposed does not cause any problem, and the method would just do nothing. Just make sure to close them in the right order, i.e. closing the writer before the stream.