StreamReader how do I move to BOF?

  • Thread starter Thread starter Johnnie Walker
  • Start date Start date
J

Johnnie Walker

Hello, I am using StreamReader.ReadLine() to read a text file.

I need a way to move the "pointer" back to the BOF (Beginning of File)
without having to close the object and create a new instance.

Is there any way of doing this? or is there another class within the
framework that will allow me to achieve this?

Any thoughts/ideas would be greatly appreciated

Thanks

JT.
 
Uzytkownik "Johnnie Walker said:
Hello, I am using StreamReader.ReadLine() to read a text file.

I need a way to move the "pointer" back to the BOF (Beginning of File)
without having to close the object and create a new instance.

Is there any way of doing this? or is there another class within the
framework that will allow me to achieve this?

If your StreamReader bases on FileStream (or another stream that has working
property Position)you can set Position of the base stream to 0, for example:

class Test
{
public void ReadStreamManyTimes()
{
string path = @"H:\tmp\Test.txt";
using (FileStream fs = new FileStream(path, FileMode.Open))
{
StreamReader reader = new StreamReader(fs);

for (int i = 0; i < 5; i++)
{
ReadAllLines(reader);
reader.BaseStream.Position = 0;
}
}
}

private void ReadAllLines(StreamReader reader)
{
while(!reader.EndOfStream)
{
string oneLine = reader.ReadLine();
System.Console.WriteLine(oneLine);
}
}
}


Best regards,
Grzegorz
 
Thanks a lot! very useful!
Grzegorz said:
If your StreamReader bases on FileStream (or another stream that has working
property Position)you can set Position of the base stream to 0, for example:

class Test
{
public void ReadStreamManyTimes()
{
string path = @"H:\tmp\Test.txt";
using (FileStream fs = new FileStream(path, FileMode.Open))
{
StreamReader reader = new StreamReader(fs);

for (int i = 0; i < 5; i++)
{
ReadAllLines(reader);
reader.BaseStream.Position = 0;
}
}
}

private void ReadAllLines(StreamReader reader)
{
while(!reader.EndOfStream)
{
string oneLine = reader.ReadLine();
System.Console.WriteLine(oneLine);
}
}
}


Best regards,
Grzegorz
 
Johnnie Walker said:
Thanks a lot! very useful!

I don't know if you saw my reply, but Grzegorz's reply is insufficient. It
does not account for the possibility of buffering within the StreamReader.
You may use the Position property as he suggests, rather than the Seek()
method I mentioned in my post, but in either case you need to call
DiscardBufferedData() to ensure that when you read from the StreamReader
after changing the position, you are actually reading from the new position.

And of course it should go without saying that you should either make sure
that you are always using a seekable stream (if you are always opening a
disk file, this should be the case), or check the CanSeek property of the
stream, or be prepared for a NotSupportedException being thrown. Not all
Streams are seekable.

Pete
 
Back
Top