Marat Faskhiev
Marat Faskhiev

Reputation: 1302

StreamReader and Dispose

I have a method, that takes Stream as parameter:

public void Method(Stream stream)
{
...
}

In this method I create StreamReader. Should I enclouse StreamReader usage in using statement? If so, stream will be disposed, that is incorrect. What is the best practise of using Stream and StreamReader in this case?

Upvotes: 3

Views: 2579

Answers (3)

Marcin Deptuła
Marcin Deptuła

Reputation: 11977

In such cases, I tend to write something like this and the end of method:

streamWriter.Flush(); // Only for writers, not for readers
streamWriter = null; // Show myself and other coders that lack of Dispose is not a mistake but it's intented

That approach is what I use for stream decorators that always dispose underlying streams, it's worth to mention, that in some cases (for example - DeflateStream) you need to call .Dispose(), but in such cases, stream decorators allows you to choose you want them to close underlying stream or not. It might look like this:

DeflateStream deflateStream = new DeflateStream(fileReader.BaseStream, CompressionMode.Decompress, true);
BinaryReader deflateReader = new BinaryReader(deflateStream);
var articleText = deflateReader.ReadString();
deflateReader = null;
deflateStream.Close();
deflateStream.Dispose();
deflateStream = null;

Upvotes: 2

Nick
Nick

Reputation: 25828

Calling Dispose on the StreamReader will dispose the underlying Stream. If this is what you want then wrap the StreamReader in the using construct. Otherwise just construct the StreamReader and leave it for the garbage collector to clean up.

In other words, it depends on whether your function is 'taking ownership of' the Stream.

Upvotes: 2

RQDQ
RQDQ

Reputation: 15579

Nope - in this case it's traditional for the caller to do the disposing.

Upvotes: 4

Related Questions