Friday, February 27, 2009

Reset StreamReader in C#

Hello,

This is a little bit weired, but it works.

During reading a file, I wanted to reset file pointer to start from the begining of a file. I used FileStream and StreamReader in C#.

My initial ideal was to call these two functions;

FileStream fs;
StreamReader sr;
:
:
:
fs.Seek(0, SeekOrigin.Begin);
sr.BaseStream.Seek(0, SeekOrigin.Begin);


However, this didn't work although I checked fs.Position == 0 and sr.BaseStream.Position == 0.

Finally, I solved this problem as follows;

FileStream fs;
StreamReader sr;
:
:
:
fs.Seek(0, SeekOrigin.Begin);
sr.DiscardBufferedData();
sr.BaseStream.Seek(0, SeekOrigin.Begin);
sr.BaseStream.Position = 0;


Frankly, I can't understand why I need to use these three lines for resetting StreamReader. But, anyway it works well, and I can start to read from the begining of a file.

No comments: