Chris
Chris

Reputation: 3519

Return StreamReader to Beginning

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.

Upvotes: 95

Views: 129633

Answers (8)

saad bin sami
saad bin sami

Reputation: 454

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);
 }

Upvotes: 3

Eamon
Eamon

Reputation: 1909

Amy's answer will work on some files but depending on the underlying stream's encoding, you may get unexpected results.

For example if the stream is UTF-8 and has a preamble, then the StreamReader will use this to detect the encoding and then switch off some internal flags that tells it to detect the encoding and check the preamble. If you reset the stream's position to the beginning, the stream reader will now consume the preamble again but it will include it in the output the second time. There is no public methods to reset this encoding and preamble state so the safest thing to do if you need to "rewind" a stream reader is to seek the underlying stream to the beginning (or set position) as shown and create a new StreamReader, just calling DiscardBufferedData() on the StreamReader will not be sufficient.

Upvotes: 33

Mauricio Kenny
Mauricio Kenny

Reputation: 93

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);
}

Upvotes: 0

Md Shahriar
Md Shahriar

Reputation: 2786

The question is looking for some kind of StreamReader.Rewind() method. You are looking for StreamReader.BaseStream.Position = 0; which sets the reader back to the beginning so it can be read again.

StreamReader sr = new StreamReader("H:/kate/rani.txt");

Console.WriteLine(sr.ReadToEnd());

sr.BaseStream.Position = 0;

Console.WriteLine("----------------------------------");

while (!sr.EndOfStream)
{
    Console.WriteLine(sr.ReadLine());
}

Upvotes: 1

vyv
vyv

Reputation: 19

public long ReadList(string fileName, Action<string> action,long position=0)
{
  if (!File.Exists(fileName)) return 0;

  using (var reader = new StreamReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),System.Text.Encoding.Unicode))
  {
    if (position > 0)reader.BaseStream.Position = position;

     while (!reader.EndOfStream)
     {
       action(reader.ReadLine());
     }
     return reader.BaseStream.Position;
   }
}

Upvotes: 1

Hance Doofenshmirts
Hance Doofenshmirts

Reputation: 631

I use this method:

System.IO.StreamReader reader = new System.IO.StreamReader("file.txt")
//end of reading
reader.DiscardBufferedData();
reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); 

Upvotes: 63

user47589
user47589

Reputation:

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

Upvotes: 136

TehBoyan
TehBoyan

Reputation: 6900

This is all good if the BaseStream can actually be set Position property to 0.

If you cannot (example would be a HttpWebResponse stream) then a good option would be to copy the stream to a MemoryStream...there you can set Position to 0 and restart the Stream as much as you want.

Upvotes: 19

Related Questions