有没有更好的方法来统计文本文件中的行数?

11

以下是我一直在使用的代码。虽然它确实可以工作,但当尝试计算较大的文件(比如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
3个回答

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

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

请参考这个问题。


1
非常好......我需要对它进行一些调整以适应VB,但与之前相比好像天壤之别! - Muhnamana
5
哈哈,微调了一下。答案已经在VB中了,但他只是不小心加了一个分号。抱歉,我笑出声了,不得不指出这一点。 - Suamere

2
即使你让迭代变得尽可能高效,如果你给它一个足够大的文件,应用程序在执行工作时仍会冻结。
如果你想避免锁定,可以生成新线程并异步执行工作。如果你正在使用.NET 4.0,你可以使用Task类轻松实现这一点。

0
TextBox2.Text = File.ReadAllLines(scannerfilePath).Length.ToString()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接