2010-09-17 164 views
2

这是在.NET中读取大型csv文件的最高性能方式? 使用FileStream?或另一类? 谢谢!阅读大型csv文件

+1

我真诚地希望你[不滚动自己的CSV分析器(http://secretgeek.net/csv_trouble.asp)。 – 2010-09-17 14:19:55

回答

1

如果你想把它全部读入内存,一个简单的File.ReadAllText()将会很好。

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

+0

是的,但如果文件很大,最好逐行阅读 – 2010-09-17 14:11:33

+0

阅读大文件的“正确风格”是什么? – 2010-09-17 15:00:49

3

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

这样做的最有效的方法是利用递延执行的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)); 

     } 
    } 
} 
+0

当你可以在你的第二个代码块中简单地使用'While(line = streamReader.ReadLine()!= null)'时,这看起来就像很多典礼。 – 2010-09-17 15:06:42