Is there a better way to count the lines in a text file?

Muhnamana picture Muhnamana · May 10, 2012 · Viewed 53.8k times · Source

Below is what I've been using. While it does work, my program locks up when trying to count a rather large file, say 10,000 or more lines. Smaller files run in no time.

Is there a better or should I say faster way to count the lines in a text file?

Here's what I'm currently using:

    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

Answer

gliderkite picture gliderkite · May 10, 2012
Imports System.IO.File 'At the beginning of the file

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

See this question.