Question Read last line of csv file

solfinker

Well-known member
Joined
Aug 6, 2013
Messages
71
Programming Experience
Beginner
Hello!
I'm trying to read the last five lines of a csv file and I'm encountering problems with the last one. I'm using the following code:


fName = "c:\temp\filexx.csv"
If System.IO.File.Exists(fName) = True Then
Dim tmpstream As StreamReader = File.OpenText(fName)
Dim lineCount = File.ReadAllLines(fName).Length
TextLine = tmpstream.ReadToEnd().Split(Environment.NewLine)
SplitLine = Split(TextLine(0), ",")
For X = 0 To 4
strline = TextLine(lineCount - X - 1).Split(",") 'trying to read the last 5 lines
For Y = 0 To 5 '6 columns
P1(X, Y) = strline(Y) 'P1 is the array where I want the data
Next
Next
tmpstream.Close() 'close reader
Else
MsgBox("File doesn't exist")
End If

This way the program reads the five next to last lines. I've I changed strline = TextLine(lineCount - X - 1).Split(",") to strline = TextLine(lineCount - X).Split(",") and the program breaks at P1(X, Y) = strline(Y) , because index out of the bounds of the array strline(Y)

I appreciate your understanding and your help.
 
Last edited:
This is crazy:
VB.NET:
Dim lineCount = File.ReadAllLines(fName).Length
TextLine = tmpstream.ReadToEnd().Split(Environment.NewLine)
What does File.ReadAllLines do? It reads all the lines of the file into a String array? Why would you then just get the length of that array and toss the array away, only to read the whole file again and then split it into lines yourself? You only need to read the file once. There are a number of changes that I'd make to that code but at the very least, change those two lines to this:
VB.NET:
TextLine = File.ReadAllLines(fName)
Dim lineCount = TextLine.Length
Now, why do you have a For loop starting at 0? You know the number of lines in the array so you can easily calculate the index of the fifth last line and the index of the last line. There's the limits for your For loop.
 
Thanks a lot!
The limits of my loop are the limits of the array I'm filling in.
I'll take a look at your code later on, as now is NSFW
Thanks again.
 
The limits of my loop are the limits of the array I'm filling in.

But why start the loop at 0 when the first line you want to read the fifth last? Start the loop at the fifth last index. It's simple arithmetic to work out what that is.
 
I really appreciate your help.
The number of lines of my array differs from the number of lines of the file I'm trying to read.
Do you prefer the loop this way?
For X = 4 To 0 Step -1
strline = TextLine(lineCount - X - 1).Split(",")
For Y = 0 To 5 '6 columns
P1(X, Y) = strline(Y)
Next
Next

I am now using your hint to avoid reading the file twice.
TextLine = File.ReadAllLines(fName)
Dim lineCount = TextLine.Length
Thank you!
 
I'm trying to read the last five lines of a csv file
Dim lines = IO.File.ReadAllLines("data.csv")
Dim last5 = lines.Skip(lines.Count - 5)
 
Back
Top