gubbfett
gubbfett

Reputation: 2177

StreamReader read spcified line number

I have found hundreds of answers reading line by line, but not one where you can specify the line you want to read. Say that my file looks like this:

A
B
C
D
E

and i want to read line #3 (in this case actually line 2 i guess - lets say I want the "C").

How do i do that?

I can of course make a loop and stop at the selected row, but isn't there a better (less ugly) way of doing this? Like MyStreamReader.Row(2).Read or something similar?

Upvotes: 0

Views: 2938

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

The most efficient approach is streaming the lines and count each line. With File.ReadAllLines you must wait for the whole array of strings be returned before you can access the array.

An easy approach is using File.ReadLines which works similar to a stream reader:

Dim thirdLine = File.ReadLines(path).ElementAtOrDefault(2)

Enumerable.ElementAtOrDefault returns Nothing if the specified index is too large. So you can check it in this way:

If thirdLine IsNot Nothing Then
    Console.WriteLine("Third line: " & thirdLine)
Else
    Console.WriteLine("The file doesn't contain 3 lines")
End If

Upvotes: 1

Related Questions