Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell when I've reached the end of the file when using the ReadBlock method in C#?

I noticed that it will keep returning the same read characters over and over, but I was wondering if there was a more elegant way.

like image 593
abw333 Avatar asked Jun 23 '11 13:06

abw333


4 Answers

while(!streamReader.EndOfStream)
{
    string line = streamReader.ReadLine();
    Console.WriteLine(line);
}
Console.WriteLine("End of File");
like image 113
harryovers Avatar answered Nov 13 '22 17:11

harryovers


Check StreamReader.EndOfStream. Stop your read loop when this is true.

Make sure your code correctly handles the returned value for "byte count just read" on ReadBlock calls as well. Sounds like you are seeing zero bytes read, and just assuming the unchanged buffer contents you see is another read of the same data.

like image 5
Steve Townsend Avatar answered Nov 13 '22 16:11

Steve Townsend


Unfortunately I can't comment on answers yet, but to the answer by "The Moof"...

Your use of cur here is misplaced, as the index parameter is for the index in buffer where writing is to begin. So for your examples it should be replaced by 0 in the call to stream.ReadBlock.

like image 2
PL-Li2 Avatar answered Nov 13 '22 15:11

PL-Li2


When the returned read length is less than your requested read length, you're at the end. You also should be keeping track of the read length in case your stream size isn't a perfect match for your buffer size, so you need to account for the shorter length of the data in your buffer.

do{
     len = stream.ReadBlock(buffer, 0, buffer.Length);
     /* ... */
  }while(len == buffer.Length);

You could also check the EndOfStream flag of the stream in your loop condition as well. I prefer this method since you won't do a read of '0' length (rare condition, but it can happen).

do{
      len = stream.ReadBlock(buffer, 0, buffer.Length);
      /* ... */
  }while(!stream.EndOfStream);
like image 2
The Moof Avatar answered Nov 13 '22 16:11

The Moof