Thursday, September 30, 2010

Getlines Count In A File - How To Do It In VB.Net And Linq

The follow combination of VB.Net and LINQ sample code, to count the number of rows in an input file, by using IO.File.ReadLines, which return Type System.Collection.Generic.IEnumerable(Of String), in .Net Framework 4.


To get the number of lines of a file.
Private Function GetLinesCount(ByVal FileName As String) As Integer 
    If Not File.Exists(FileName) Then 
        Return 0
        Exit Function
    End If
 

    Dim lines = (From l In IO.File.ReadLines(FileName) _
                           
Select l)
                           

    Dim d As Integer = lines.Count

    lines =Nothing
    Return
d
End Function

To skip blank line from count
Private Function GetLinesCount(ByVal FileName As String) As Integer 
    If Not File.Exists(FileName) Then 
        Return 0
        Exit Function
    End If
 

    Dim lines = (From l In IO.File.ReadLines(FileName) Where Not l.Trim.Length = 0 _
                           
Select l)
                           

    Dim d As Integer = lines.Count

    lines =Nothing
    Return
d
End Function
Permanent link