Using StreamReader.Peek()

  • Thread starter Thread starter Shawn
  • Start date Start date
S

Shawn

Hi. I'm using this code to loop through all the lines in a text field:
While myStreamReader.Peek() > -1
myStreamReader.ReadLine()
i = i + 1
End While

Now, what I need to do is to loop through all the lines one more time and do
the work that I'm supposed to do. The reason for this is that I have to
know how many lines exists in the text file in order to display a
ProgressBar to the user. I've tried setting
myStreamReader.BaseStream.Seek(0, SeekOrigin.Begin) but
myStreamReader.Peek() just returns -1.

Is it not possible to achieve this without having to close the FileStream
and create a new one?

Thanks,
Shawn
 
Do you have to use Peek()? I'd do it like this

While Not myStreamReader.ReadLine() Is Nothing
i = i + 1
End While

I don't know it that's any more Seek friendly though.



Mattias
 
ProgressBar to the user. I've tried setting
myStreamReader.BaseStream.Seek(0, SeekOrigin.Begin) but
myStreamReader.Peek() just returns -1.


You might try setting the Position property of the base stream to 0:

myStreamReader.BaseStream.Position = 0

I don't know if that will work in this situation though.

Are the lines in the file all the same length? If so, you can get the
number of lines by dividing the length of the file by the line size.

Another method for handling a progress bar is to set the progress bar with
a max value of 100. Then each time you read a line, take the length of the
line and divide it by the length of the file and multiply by 100. Then
increment the progress bar's value by that amount. That way you don't have
to read through every line in the file beforehand:

'This is untested code
myProgressBar.Value = 0
While myStreamReader.Peek <> -1
strLine = myStreamReader.ReadLine()
intPercent = (strLine.Length / myStreamReader.BaseStream.Length) * 100

'Do something with strLine here

'Update the progress bar
myProgressBar.Value += intPercent
End While

Hope this helps a little
 
You could also try the following:

myProgressBar.Value = 0
While myStreamReader.Peek <> -1
strLine = myStreamReader.ReadLine()
intPercent = (myStreamReader.BaseStream.Position * 100 ) /
myStreamReader.BaseStream.Length

'Do something with strLine here

'Update the progress bar
myProgressBar.Value += intPercent
End While

I actually tried this and its works fine.
 

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

Back
Top