我有一个1 GB的文本文件,我需要逐行阅读。执行此操作的最佳和最快方法是什么?
private void ReadTxtFile()
{
string filePath = string.Empty;
filePath = openFileDialog1.FileName;
if (string.IsNullOrEmpty(filePath))
{
using (StreamReader sr = new StreamReader(filePath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
FormatData(line);
}
}
}
}
在FormatData()
中,我检查行的起始字,它必须与一个字匹配,并在此基础上递增一个整数变量。
void FormatData(string line)
{
if (line.StartWith(word))
{
globalIntVariable++;
}
}
发布于 2010-11-25 12:29:31
如果您使用的是.NET 4.0,请尝试MemoryMappedFile,它是为此场景设计的类。
否则,您可以使用StreamReader.ReadLine
。
发布于 2010-11-26 22:25:45
您可以使用LINQ
int result = File.ReadLines(filePath).Count(line => line.StartsWith(word));
File.ReadLines返回一个IEnumerable,它懒惰地从文件中读取每一行,而不将整个文件加载到内存中。
Enumerable.Count计算以单词开头的行数。
如果从UI线程调用,请使用BackgroundWorker。
发布于 2010-11-25 12:26:01
StreamReader.ReadLine
应该可以很好地工作。让框架选择缓冲,除非您通过分析知道可以做得更好。
https://stackoverflow.com/questions/4273699
复制相似问题