我正在使用 System.IO.File.ReadAllLines(TextFileURL) 在 vb.net 中讀取一個大文本檔案。由于該程序需要幾秒鐘才能完成,是否有可能使用進度條?
.
RawFile = System.IO.File.ReadAllLines(TextFileURL)
lines = RawFile.ToList
If arg = "" Then MsgBox("IMPORTER IS DONE")
.
沒有回圈或任何可用于更新進度條值的東西。任何想法或解決方法將不勝感激。
uj5u.com熱心網友回復:
下面逐行讀取一個相當大的 .TXT 檔案并報告進度:
代碼:
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
結果:

筆記:
- 這給流帶來了負擔,因為最終讀取一行是小資料
- 嘗試使用緩沖流來降低壓力
- 請注意,我僅在整數百分比大于上一個時報告
- 否則更新進度條時你會淹沒 UI
- 有微不足道的異步使用,您可能希望整體改進
- 進度條沒有完全達到 100%,我讓你解決這個問題,這很容易做到
uj5u.com熱心網友回復:
當您處理非常大的檔案時,您可以使用ReadLines而不是ReadAllLines
像檔案ReadLines所說的那樣,可以更有效:
Dim lstOflines as List(Of String)
For Each line As String In File.ReadLines(TextFileURL)
lstOflines.Add(line)
Next line
要獲取總行數,您可以根據檔案大小進行猜測,而不是處理檔案的兩倍
- 獲取檔案大小的代碼:(在開始處理之前使用)
Dim myFile As New FileInfo(TextFileURL)
Dim sizeInBytes As Long = myFile.Length
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450122.html
