如何使用Stream阅读器c#逐行正确读取文件

时间:2015-11-12 13:11:21

标签: c# file streamreader

如何逐行读取文件中的文本?

我使用的代码是在第一次旋转时读取第一行和第二行。 以下不起作用,因为它在方法sr.ReadLine()中返回两个不同的字符串。 ReadLine()方法是从文件而不是当前行获取下一行吗?

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

2 个答案:

答案 0 :(得分:4)

您在循环中使用ReadLine两次。将StreamReader.ReadLine的返回值存储在字符串变量中。否则,你正在推动读者进入下一行。

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

答案 1 :(得分:1)

我知道你已经有了答案,但我只想指出你可以使用Linq更简洁地编写整个方法:

var minimumDateTime = times[this.Step].AddMinutes(-different);
var maximumDateTime = times[this.Step].AddMinutes(different);

var linesInDateRange = 
    from   line in System.IO.File.ReadLines(this.File)
    let    info = line.Split(new[] {", ", ",", "\""}, StringSplitOptions.RemoveEmptyEntries)
    let    thisTime = DateTime.ParseExact(info[FileConstants.DATE], "yyyy-M-d H:m:s", null)
    where  thisTime > minimumDateTime && thisTime < maximumDateTime
    select line;

var allInformation = linesInDateRange.ToList();