【发布时间】:2010-09-17 14:04:23
【问题描述】:
在 .NET 中读取大型 csv 文件的最佳方式是什么? 使用文件流?或其他类? 谢谢!
【问题讨论】:
在 .NET 中读取大型 csv 文件的最佳方式是什么? 使用文件流?或其他类? 谢谢!
【问题讨论】:
您可以使用FileInfo.OpenText返回的StreamReader:
Dim file As New FileInfo("path\to\file")
Using reader As StreamReader = file.OpenText()
While Not reader.EndOfStream
Dim nextLine As String = reader.ReadLine()
ProcessCsvLine(nextLine)
End While
End Using
【讨论】:
最有效的方法是利用 LINQ 中的延迟执行。您可以创建一个简单的 Linq-To-Text 函数,一次读取一行,处理它然后继续。这真的很有帮助,因为文件非常大。
我会停止使用 StreamReader 类的 ReadBlock 或 ReadBlock 或 ReadToEnd 方法,因为它们倾向于一次读取多行甚至文件中的整行。与一次读取一行相比,这最终会消耗更多的内存。
public static IEnumerable<string> Lines(this StreamReader source)
{
String line;
if (source == null)
throw new ArgumentNullException("source");
while ((line = source.ReadLine()) != null)
{
yield return line;
}
}
请注意,该函数是 StreamReader 类的扩展方法。这意味着它可以按如下方式使用:
class Program
{
static void Main(string[] args)
{
using(StreamReader streamReader = new StreamReader("TextFile.txt"))
{
var tokens = from line in streamReader.Lines()
let items = line.Split(',')
select String.Format("{0}{1}{2}",
items[1].PadRight(16),
items[2].PadRight(16),
items[3].PadRight(16));
}
}
}
【讨论】:
While (line = streamReader.ReadLine() != null) 时,这似乎是一种仪式。
【讨论】:
我正在使用这个库来阅读 Csv。这个真的很好用
http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
【讨论】: