[英]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()
. 以下内容不起作用,因为它在方法
sr.ReadLine()
返回了两个不同的字符串。 Does the ReadLine()
method take the next line from file rather than the current line? 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());
}
}
}
You are using ReadLine
two times in the loop. 您在循环中两次使用
ReadLine
。 Store the return value of StreamReader.ReadLine
in a string variable. 将
StreamReader.ReadLine
的返回值存储在字符串变量中。 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);
}
}
I know you already have the answer, but I just wanted to point out that you can write that entire method more succinctly using Linq like this: 我知道您已经有了答案,但我只想指出,您可以像这样使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.