Results 1 to 6 of 6

Thread: Number of lines in a sequential file

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2020
    Posts
    62

    Number of lines in a sequential file

    How do I know how many lines are in a sequential text file?
    Or how to read the file one line at a time so I can count the lines in the read.

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Number of lines in a sequential file

    Code:
    IO.File.ReadAllLines("path").Length
    will return the number of lines in the file

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Number of lines in a sequential file

    To read line by line...

    Code:
    Dim counter As Integer = 0
    Using reader As StreamReader = New StreamReader("path")
        While Not reader.EndOfStream
            reader.ReadLine ' this reads the line, but the string read isn't used
            counter += 1
        End While
    End Using
    
    msgbox(counter)

  4. #4

    Thread Starter
    Member
    Join Date
    Sep 2020
    Posts
    62

    Re: Number of lines in a sequential file

    That's what I was looking for, Thank You.

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Number of lines in a sequential file

    Quote Originally Posted by .paul. View Post
    Code:
    IO.File.ReadAllLines("path").Length
    will return the number of lines in the file
    You would probably be better off with this:
    vb.net Code:
    1. IO.File.ReadLines("path").Count()
    Your code doesn't use the data read from the file so why create an array containing it all? That would be especially bad for a large file. ReadLines will read the file one line at a time and discard each one before reading the next, so it is far more memory-efficient. I'm not sure whether there would be a difference in performance though. Probably not much if there is but I've never tested.

    ReadLines requires .NET Framework 4.0 or later or .NET Core 1.0 or later.

  6. #6

    Thread Starter
    Member
    Join Date
    Sep 2020
    Posts
    62

    Re: Number of lines in a sequential file

    Great, I am using that now. Thank You

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width