Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will closing a FileStream close the StreamReader?

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();
    }
}
like image 660
norlando Avatar asked Nov 24 '09 19:11

norlando


People also ask

Does closing a StreamReader close the underlying stream?

Yes, StreamReader , StreamWriter , BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them.

What does Filestream close () do?

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

What happens if StreamReader is not closed?

@IvanLi It automatically disposes of the StreamWriting. Anything declared in a using statement is disposed of when the statement ends.

How does a StreamReader differ from a StreamWriter?

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".


1 Answers

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);
            }
        }
    }
}
like image 113
Brian Avatar answered Nov 16 '22 00:11

Brian