Search code examples
c#filestreamreader

How can read correctly file line by line using Stream reader c#


How can read text from a file line by line?

This code who I used is read first and second line in first rotation. The following isn't working as it's returning two different strings in method sr.ReadLine(). Does the ReadLine() method take the next line from file rather than the current line?

List<string> allInformation = new List<string>();
DateTime minimumDateTime = times[this.Step].AddMinutes(-different);
DateTime maximumDateTime = times[this.Step].AddMinutes(different);

using (FileStream fs = System.IO.File.Open(this.File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
    DateTime thisTime;
    string[] info = new string[6];

    while (sr.Peek() >= 0)
    {
        info = sr.ReadLine().Split(new string[] { ", ", ",", "\"" }, StringSplitOptions.RemoveEmptyEntries);
        thisTime = DateTime.ParseExact(info[FileConstants.DATE], "yyyy-M-d H:m:s", null);

        if (thisTime > minimumDateTime && thisTime < maximumDateTime)
        {
            allInformation.Add(sr.ReadLine());
        }
    }
}

Solution

  • You are using ReadLine two times in the loop. Store the return value of StreamReader.ReadLine in a string variable. Otherwise you are advancing the reader to the next line.

    while (sr.Peek() >= 0)
    {
        string line = sr.ReadLine();
        info = line.Split(new string[] { ", ", ",", "\"" }, StringSplitOptions.RemoveEmptyEntries);
        thisTime = DateTime.ParseExact(info[FileConstants.DATE], "yyyy-M-d H:m:s", null);
    
        if (thisTime > minimumDateTime && thisTime < maximumDateTime)
        {
            allInformation.Add(line);
        }
    }