Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 216
Muhnamana Avatar asked May 10 '12 17:05

Muhnamana


2 Answers

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

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

See this question.

like image 105
gliderkite Avatar answered Nov 09 '22 02:11

gliderkite


Even if you make your iteration as efficient as can be, if you hand it a large enough file you're going to make the application freeze while it performs the work.

If you want to avoid the locking, you could spawn a new thread and perform the work asynchronously. If you're using .NET 4.0 you can use the Task class to make this very easy.

like image 35
Justin Helgerson Avatar answered Nov 09 '22 02:11

Justin Helgerson