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.
while(!streamReader.EndOfStream)
{
string line = streamReader.ReadLine();
Console.WriteLine(line);
}
Console.WriteLine("End of File");
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.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With