读取大型csv文件

时间:2010-09-17 14:04:24

标签: vb.net file csv

哪种在.NET中读取大型csv文件的性能最高? 使用FileStream?还是另一课? 谢谢!

5 个答案:

答案 0 :(得分:3)

您可以使用StreamReader返回的FileInfo.OpenText

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

最有效的方法是利用LINQ中的deffered执行。您可以创建一个简单的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));

       }
   }
}

答案 3 :(得分:1)

我对这个图书馆有很好的经验:

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

答案 4 :(得分:0)

相关问题