2012-05-10 56 views
8

下面是我一直在使用的。虽然它确实有效,但当我试图计算一个相当大的文件时,我的程序就会锁定,例如10,000或更多行。小文件立即运行。有没有更好的方法来计算文本文件中的行数?

有没有更好的或应该说更快的方式来计算文本文件中的行数?

这里就是我目前使用:

Dim selectedItems = (From i In ListBox1.SelectedItems).ToArray() 
    For Each selectedItem In selectedItems 
     ListBox2.Items.Add(selectedItem) 
     ListBox1.Items.Remove(selectedItem) 

     Dim FileQty = selectedItem.ToString 
     'reads the data file and returns the qty 
     Dim intLines As Integer = 0 
     'Dim sr As New IO.StreamReader(OpenFileDialog1.FileName) 
     Dim sr As New IO.StreamReader(TextBox1_Path.Text + "\" + FileQty) 
     Do While sr.Peek() >= 0 
      TextBox1.Text += sr.ReadLine() & ControlChars.CrLf 
      intLines += 1 
     Loop 
     ListBox6.Items.Add(intLines) 
    Next 

回答

27
Imports System.IO.File 'At the beginning of the file 

Dim lineCount = File.ReadAllLines("file.txt").Length 

this问题。

+0

非常好...我不得不为VB调整它,但它似乎像来自以前的日夜! – Muhnamana

+3

哈哈,调整。答案已经在VB中,但他只是不小心添加了分号。对不起,我违法了,不得不指出。 – Suamere

2

即使您尽可能高效地进行迭代,如果您将足够大的文件传递给它,您将在应用程序执行时冻结应用程序。

如果你想避免锁定,你可以产生一个新的线程并异步执行工作。如果您使用的是.NET 4.0,则可以使用Task类来实现这一点非常简单。

0
TextBox2.Text = File.ReadAllLines(scannerfilePath).Length.ToString() 
相关问题