2012-05-10 123 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() 
相關問題