【问题标题】:Reading large csv files读取大型 csv 文件
【发布时间】:2010-09-17 14:04:23
【问题描述】:

在 .NET 中读取大型 csv 文件的最佳方式是什么? 使用文件流?或其他类? 谢谢!

【问题讨论】:

标签: vb.net file csv


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    如果你想把它全部读入内存,一个简单的File.ReadAllText() 就可以了。

    编辑:如果您的文件确实非常大,那么您可以使用StreamReader 类,详情请参阅here。这种方法有时是不可避免的,但出于风格原因,应该尽量避免。请参阅here 进行更深入的讨论。

    【讨论】:

    • 是的,但如果文件很大,最好逐行阅读
    【解决方案3】:

    最有效的方法是利用 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) 时,这似乎是一种仪式。
    【解决方案4】:

    我对这个库有很好的体验:

    http://www.codeproject.com/KB/database/CsvReader.aspx

    【讨论】:

      【解决方案5】:

      我正在使用这个库来阅读 Csv。这个真的很好用

      http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-26
        • 2021-09-02
        • 2020-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-10
        • 2014-11-15
        相关资源
        最近更新 更多