Navigating in a textfile with StreamReader?

  • Thread starter Thread starter Jaga
  • Start date Start date
J

Jaga

Hi,

how can I read the same passage in a textfile several times?

I'm writing a little textgenerator. It reads lines from a file, replaces
the variables, and writes it in an other file. Some lines I have to read
several times and write them with other values.

What is wrong with this code:
using (StreamWriter swr = new StreamWriter(outPath))
{
using (StreamReader srd = new StreamReader(inPath,
System.Text.Encoding.Default, false))
{
long offset;
string line;
while ((line = srd.ReadLine()) != null)
{
switch (line)
{
case "XY...":
//mark the position
offset = srd.BaseStream.Position;
break;
case "YZ...":
if (...)
{
//jump back to the position
srd.BaseStream.Position = offset;
srd.DiscardBufferData();
}
break;
}
...
}
}
}

thanks

Jaga
 
Jaga said:
how can I read the same passage in a textfile several times?

I'm writing a little textgenerator. It reads lines from a file, replaces
the variables, and writes it in an other file. Some lines I have to read
several times and write them with other values.

What is wrong with this code:

<snip>

You're using the base stream's position to calculate where to "seek"
to, which may well be inaccurate because more will have been buffered.

Unfortunately if you don't *really* know where you want to seek to, the
seeking part (setting the position and then discarding the buffered
data) won't help much.

I can't immediately think of an easy way round this problem.
 
Hi Jaga,

If you are reading on a by line basis you could read all the lines in a
memory structure, like an ArrayList for example and then have a pointer to
the current processing line, in this way when you finish with the current
line all you have to do is increment it. , in this way you can place marks
as they will be indexes in the ArrayList .

Hope this help,
 
Hi Ignacio,

I wish, I could solve the problem by StreamReader itself, but it is a really
good idea, I try it.

thanks,
Jaga


PS: A read command of the StreamReader updates not the property "Position"
of the BaseStream, but it updates an internal Field "charPos". Do anybody
knows why Microsoft dosn't make it public?
 
Back
Top