'Reading line count using VB.NET

How to calculate the number of rows in a file which we have uploaded. The file might be either a text file or a CSV or Excel file.

I'm using the folowing code to get the record count like this:

Dim FileCount = From lin1 As String In File.ReadAllLines(hidFilePath.Value.ToString())
Let dd = lin1.Count
Select dd
Dim file_count As Integer =  FileCount.Count

but in some cases the count is wrong.



Solution 1:[1]

ReadAllLines returns a string array, so you can simply take the length of the array.

Dim file_count As Integer = _
    File.ReadAllLines(hidFilePath.Value.ToString()).Length

Solution 2:[2]

EDIT: read question to fast and answered with a loop solution

You can set your linecount as an integer and have the reader read to the end of the file.

Dim sr As New StreamReader("file path here")    
Dim lineCount As Integer = System.Text.RegularExpressions.Regex.Split(sr.ReadToEnd(), Environment.NewLine).Length
sr.Close() 

You can use a count variable and loop through the file until theres nothing

        ''name count and set it to 0
        Dim count As Integer
        count = 0  
        Dim obj As StreamReader
        obj = New StreamReader("C:\...\source.txt")
        ''loop through the file until the end
        Do Until obj.ReadLine Is Nothing
            count = count + 1
        Loop
        ''close file and show count
        obj.Close()
        MessageBox.Show(count)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RB.
Solution 2