11

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
Muhnamana
  • 1,014
  • 13
  • 34
  • 57

3 Answers3

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

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

See this question.

Community
  • 1
  • 1
gliderkite
  • 8,828
  • 6
  • 44
  • 80
  • 1
    Very nice...I had to tweak it a bit for VB but it seems like day and night from before! – Muhnamana May 10 '12 at 17:56
  • 5
    Lol, tweak. The answer was already in VB, but he just accidentally added the Semicolon. Sorry, I lawl'd and had to point that out. – Suamere Aug 07 '13 at 21:39
2

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.

Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
0
TextBox2.Text = File.ReadAllLines(scannerfilePath).Length.ToString()
josliber
  • 43,891
  • 12
  • 98
  • 133
acidapex
  • 21
  • 1