Return StreamReader to Beginning

Viewed 112906

I'm reading a file in line-by-line and I want to be able to restart the read by calling a method Rewind().

How can I manipulate my System.IO.StreamReader and/or its underlying System.IO.FileStream to start over with reading the file?

I got the clever idea to use FileStream.Seek(long, SeekOffset) to move around the file, but it has no effect the enclosing System.IO.StreamReader. I could Close() and reassign both the stream and the reader referecnes, but I'm hoping there's a better way.

8 Answers

You need to seek on the stream, like you did, then call DiscardBufferedData on the StreamReader. Documentation here:

Edit: Adding code example:

Stream s = new MemoryStream();
StreamReader sr = new StreamReader(s);
// later... after we read stuff
s.Position = 0;
sr.DiscardBufferedData();        // reader now reading from position 0

I had created a simple method, that you can use to reset the StreamReader.

using (var reader = StreamReader(filePath))
{
   reader.ReadLine();
   reader.ReadLine();
   ResetReader(reader);
}


private static void ResetReader(StreamReader reader)

 {
     reader.DiscardBufferedData();
     reader.BaseStream.Seek(0, SeekOrigin.Begin);
 }
public static void removeDuplicatedLinesBigFile2(string inFile, string outFile)
{
    int counter1 = 0, counter2 = 0;
    string line1, line2;
    bool band = false;

    // Read the file and display it line by line.  
    System.IO.StreamReader fileIN1 = new System.IO.StreamReader(inFile);
    System.IO.StreamReader fileIN2 = new System.IO.StreamReader(inFile);
    System.IO.StreamWriter fileOut = new System.IO.StreamWriter(outFile);

    while ((line1 = fileIN1.ReadLine()) != null)
    {
        //band = false;
        int counter = 0;
        fileIN2.BaseStream.Position = 0;
        fileIN2.DiscardBufferedData();

        while ((line2 = fileIN2.ReadLine()) != null)
        {                   
            if (line1.Equals(line2))
                counter++;

            if (counter > 1)
                break;
        }

        fileOut.WriteLine(line1);
        counter1++;
    }

    fileIN1.Close();
    fileIN2.Close();
    Console.WriteLine("Total Text Rows Copied: {0}", counter1);
}
Related