sr.ReadLine() problem

P

PointMan

data is like below
1111
2222
3333
4444
5555

while((str1 = sr.ReadLine()) != null)
{
str2 = sr.ReadLine()
}

in this case
str1 read 1111 and then
str2 read 2222 and then
str1 read 3333.......

but i wanna read 2222 to str1 again.
is there any way to solve this?
 
M

Marc Gravell

Not really; they are largely sequential and forwards only...

you can "peek", but only 1 character... is this sufficient? i.e. to
notice the 3? Alternatively, how many rows do you ever need to go back?
If just the last you could keep a buffer copy of the last line?

Otherwise you may need to start again... with a stream backer this
might mean Seek() [if the stream is seekable]. Otherwise you might need
to start the stream/string again with a new reader. For this reason,
when processing input from non-seekable / repeatable sources it is
sometimes necessary to write the data to another device (e.g. a
FileStream) first, so that you can subsequently Seek().

Generally, the better design is to write your code (where possible) to
do a single pass.

Marc
 
O

Oliver Sturm

Hello PointMan,
is there any way to solve this?

Assuming that your "sr" variable is of type StreamReader, a line like this
could help you (to reset the reader to the beginning before the second
ReadLine() call):

sr.BaseStream.Seek(0, SeekOrigin.Begin);

I must admit that your algorithm isn't really clear to me - it might make
a lot more sense to restructure it, maybe change the loop type... we can
probably help you better if you describe what you want to do.


Oliver Sturm
 
S

Stephany Young

If you are saying that, as you are reading the data, each line has some of
form of relationship to the following line that needs to be taken into
account while processing the original line then you you need to change your
construct to something like this:

string str1 = sr.ReadLine();

while (str1 != null)
{

// do some magic with the line

// read the following line
str2 = sr.ReadLine()
// break if it wasn't there cos our rule has been broken
if (str2 == null)
break;

// do some magic with the following line

// simulate a ReadLine to make sure the next iteration is using the
right values
str1 = str2;
}
 
M

Morten Wennevik

Hi,

Your best bet is probably to store previous lines as long as you need them.

while((str1 = sr.ReadLine()) != null)
{
// process str1, the last line will be stored in str2
str2 = str1;
}
 

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