If I use a FileStream to create a StreamReader, will the StreamReader close when I close the FileStream or will I need to close the StreamReader too?
public void ReadFile()
{
    var file = new FileStream("c:\file.txt", FileMode.Open, FileAccess.Read);
    var reader = new StreamReader(file);
    try
    {
        txtFile.Text = reader.ReadToEnd();
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        file.Close();
    }
}
Yes, StreamReader , StreamWriter , BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them.
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
@IvanLi It automatically disposes of the StreamWriting. Anything declared in a using statement is disposed of when the statement ends.
StreamReader and StreamWriter are found in the System.IO namespace. Both classes are useful when you want to read or write character-based data. Both of these classes deal with Unicode characters. StreamReader derives from the Abstract class "TextReader" and StreamWriter derives from "TextWriter".
Essentially yes. You don't actually have to close a StreamReader. If you do, all it does is closes the underlying stream.
@Bruno makes a good point about closing the outer-most wrapper. It is good practice to close the outer-most stream and let it close underlying streams in order to ensure all resources are released properly.
From Reflector...
public class StreamReader : TextReader
{
    public override void Close()
    {
        this.Dispose(true);
    }
    protected override void Dispose(bool disposing)
    {
        try
        {
            if ((this.Closable && disposing) && (this.stream != null))
            {
                this.stream.Close();
            }
        }
        finally
        {
            if (this.Closable && (this.stream != null))
            {
                this.stream = null;
                this.encoding = null;
                this.decoder = null;
                this.byteBuffer = null;
                this.charBuffer = null;
                this.charPos = 0;
                this.charLen = 0;
                base.Dispose(disposing);
            }
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With