vb.net 有没有更好的方法来计算文本文件中的行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10539483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:06:01  来源:igfitidea点击:

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

vb.netvisual-studio-2010text-filesstreamreader

提问by Muhnamana

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.

下面是我一直在使用的。虽然它确实有效,但我的程序在尝试计算相当大的文件时会锁定,比如 10,000 行或更多行。较小的文件可以立即运行。

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

回答by gliderkite

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

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

See thisquestion.

看到这个问题。

回答by Justin Helgerson

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 Taskclass to make this very easy.

如果您想避免锁定,您可以生成一个新线程并异步执行工作。如果您使用的是 .NET 4.0,您可以使用Task类使这变得非常容易。

回答by acidapex

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