Hi,@StewartBW. Welcome to Microsoft Q&A.
To determine how many times the loop will run when using TextFieldParser in Visual Basic .NET, you could count the non-blank lines in the file.
TextFieldParser does not provide a direct method to get the number of records beforehand, but You can read the file once to count the non-blank lines. This will give you the number of iterations the loop will execute, which you can use to set the progress bar's maximum value.
This function reads the file line by line.
It returns the total count of non-blank lines.
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Class MainWindow
Sub Main(src As String, progressBar1 As ProgressBar)
Dim totalLines As Integer = CountNonBlankLines(src)
progressBar1.Maximum = totalLines
progressBar1.Value = 0
Dim MyTextParser As New FileIO.TextFieldParser(src)
MyTextParser.TextFieldType = FileIO.FieldType.Delimited
MyTextParser.SetDelimiters(",")
While Not MyTextParser.EndOfData
Dim fields As String() = MyTextParser.ReadFields()
progressBar1.Value += 1
End While
MyTextParser.Close()
End Sub
Function CountNonBlankLines(ByVal filePath As String) As Integer
Dim lineCount As Integer = 0
Using reader As New StreamReader(filePath)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If Not String.IsNullOrWhiteSpace(line) Then
lineCount += 1
End If
End While
End Using
Return lineCount
End Function
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim filePath As String = "C:\...\WpfApp1\file.csv"
Main(filePath, ProgressBar1)
tb.Text = CountNonBlankLines(filePath)
End Sub
End Class
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation enable e-mail notifications if you want to receive the related email notification for this thread.