I/O not reading the last line of a file.

A

Adam Sandler

Hello,

I'm trying to input a txt file. Each line in the text file contains a
discrete code or value -- so I want to populate the an arraylist with
each line. I've noticed a problem. The code I have never reads the
last line of the file. Here's the code:

while (!sr.EndOfStream)
{
line = sr.ReadLine();
}
sr.Close();

If the txt file has 10 lines, after this code, there are only 9 items
in the arraylist. How can I get that last line in my arraylist?
Suggestions are greatly appreciated.

Thanks!
 
M

Marc Gravell

I might be wrong, but looking at Red Gate's .NET Reflector [still
getting used to that...] EndOfStream appears to respect the buffer...?

Marc
 
A

Arne Vajhøj

Peter said:
I might be wrong, but looking at Red Gate's .NET Reflector [still
getting used to that...] EndOfStream appears to respect the buffer...?

On my computer, using Roeder's Reflection,

Same software. Lutz Roeder just gave/sold Reflector to Red Gate.

Arne
 
A

Arne Vajhøj

Peter said:
Peter said:
On Mon, 01 Sep 2008 00:01:44 -0700, Marc Gravell
I might be wrong, but looking at Red Gate's .NET Reflector [still
getting used to that...] EndOfStream appears to respect the buffer..?
On my computer, using Roeder's Reflection,

Same software. Lutz Roeder just gave/sold Reflector to Red Gate.

Well...okay. Fine. But do you know why the OP isn't getting the last
line of input?

Nope.

For that part I am like the rest - it would be nice to see a
complete example.

Arne
 
A

Adam Sandler

That's because the EndOfStream property returns information about the  
underlying stream, not the reader state itself.  The reader buffers the 
input data, and so very well may reach the end of the underlying stream  
before it's returned all of the text in the stream.  Clearly, that's  
what's happening to you.


Instead of checking the EndOfStream property, just read until you get a  
null line:

     while ((line = sr.ReadLine()) != null)
     {
     }

Pete

Thanks for the help; that worked!
 
M

Marc Gravell

Thanks for the help; that worked!- Hide quoted text -

Interesting... can you perhaps tell us which version (including SP) of
the .NET framework you are using? It *looks* like (in 3.5 SP1, at
least) the two should work the same. I'm glad it is sorted though - a
good call by Pete.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top