【发布时间】:2016-01-24 15:10:07
【问题描述】:
如何逐行读取文件中的文本?
我使用的这段代码在第一次循环中读取第一行和第二行。
以下内容不起作用,因为它在方法 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());
}
}
}
【问题讨论】:
-
您在循环中调用了两次
ReadLine。调用一次并将其分配给局部变量以供以后使用。 -
就像朱哈尔说的。读取线的两倍。这是蒂姆答案的替代方案。 stackoverflow.com/a/9643111/169714
-
我已修复并且工作正常。感谢大家的快速回答。我可以相信回复我的速度有多快。
标签: c# file streamreader