Home > other >  System.IO.File.ReadAllLines() method with progress bar in vb.net
System.IO.File.ReadAllLines() method with progress bar in vb.net

Time:03-26

I am reading a large text file in vb.net using System.IO.File.ReadAllLines(TextFileURL). Since the process takes a few seconds to finish, would there be a possibility to use a progress bar?
.
RawFile = System.IO.File.ReadAllLines(TextFileURL)
lines = RawFile.ToList
If arg = "" Then MsgBox("IMPORTER IS DONE")
.
There is no loop or anything that could be used to update the value of the progress bar. Any thoughts or workaround would be appreciated.

CodePudding user response:

The following reads a pretty big .TXT file line by line and reports progress:

Code:

Imports System.IO

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dialog As New OpenFileDialog

        dialog.Filter = "Text|*.txt"

        Dim result = dialog.ShowDialog()

        If result <> DialogResult.OK Then
            Return
        End If

        Dim stream = File.OpenRead(dialog.FileName)
        Dim reader As New StreamReader(stream)

        Dim percentage As Integer

        While True

            Dim line As String = Await reader.ReadLineAsync()

            If line Is Nothing Then
                Exit While
            End If

            ' TODO do something with your line

            Dim percentD As Double = 1D / stream.Length * stream.Position * 100D
            Dim percentI As Integer = Math.Floor(percentD)

            If percentI > percentage Then
                ProgressBar1.Value = percentI
                percentage = percentI
            End If
        End While
        Await stream.DisposeAsync()
    End Sub
End Class

Result:

enter image description here

Notes:

  • this puts a burden on the stream as ultimately reading a line is small data
    • try using a buffered stream to reduce pressure
  • notice that I only report when integer percentage is greater than previous
    • you'd overwhelm UI when updating the progress bar otherwise
  • there is trivial async usage, you may want to improve that overall
  • the progress bar doesn't exactly reach 100%, I let you fix that, it's pretty EZ to do

CodePudding user response:

You can use ReadLines instead of ReadAllLines as docs said, when you are working with very large files, ReadLines can be more efficient:

Dim lstOflines as List(Of String)
For Each line As String In File.ReadLines(TextFileURL)

    lstOflines.Add(line)

Next line

For get the total number of lines, you can make a guess based on file Size instead processing two times the file

  • Code for getting filesize: (use before start processing)
 Dim myFile As New FileInfo(TextFileURL)
 Dim sizeInBytes As Long = myFile.Length
  • Related