Using StreamReader after the underlying stream has been deleted?

Using StreamReader, if you are managing the underlying stream, I thought you could no longer read.

For this to be true, suggest this question where it suggested that you do not need to dispose of StreamWriter (in their case) if the life of the underlying stream is processed elsewhere.

But this is not so. I have done the following:

I have a file called delme.txt containing the following

 abc def ghi 

I run this:

  Stream s = File.OpenRead(@"C:\delme.txt"); StreamReader sr = new StreamReader(s, Encoding.ASCII); Console.WriteLine(sr.ReadLine()); s.Dispose(); Console.WriteLine(sr.ReadLine()); 

And the result:

 abc def 

How is this possible?

+4
source share
3 answers

Your StreamReader has already read the next line in its buffer.
It will not return to the Stream source until it runs out in its buffer.

In fact, in this case it would be impossible to exclude an exception, since there is no idempotent way to find out if Stream installed. (No IsDisposed property)

+10
source

To add @SLaks to the answer, here will demonstrate (using a file with several thousand lines of text):

  Stream s = File.OpenRead(path); StreamReader sr = new StreamReader(s, Encoding.ASCII); Console.WriteLine(sr.ReadLine()); s.Dispose(); int i = 1; try { while (!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); i++; } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(i + " lines total"); Console.ReadLine(); 

It will output many and many lines, for example, a couple of hundred, and then throw an exception. My output ended as follows:

 qrs tuv wxy zab cde fgh ijk lmn Cannot access a closed file. 204 lines total 

In fact, we see that there is a constructor for StreamReader that takes a bufferSize parameter as the fourth parameter:

 StreamReader sr = new StreamReader(s, Encoding.ASCII, false, 10000); 

Using 10000, it actually prints a total of 1248 lines for me before the crash. Also, the smallest possible value you can use is 1, in which case it still preselects 25 rows.

+5
source

What you need to understand is what it is trying to do.

http://msdn.microsoft.com/en-us/library/ms227563.aspx

It states that the TextReader will be unusable if the TextReader is finished. Perhaps, since he did not read everything, it is not considered complete; so you can continue to use it. This is my hunch.

0
source

All Articles