LukmanH
LukmanH

Reputation: 13

Vb.net File.ReadAllLines Method

I've created an application with timer that is to change the text of a label based on the contents of my file.

My text file:

00:00:05 "Some Text"    
00:00:10 "Some Text"     
00:00:25 "Some Text"

Just like a subtitle file, my form will change the label text at each of the timestamps.

I use this code to read the text file:

Dim Lines = File.ReadAllLines(MyFile)
Dim line1() As String = Lines.ElementAtOrDefault(0).Split
Dim line2() As String = Lines.ElementAtOrDefault(1).Split
Dim line3() As String = Lines.ElementAtOrDefault(2).Split

But it doesn't work on if the file has more than 3 lines.

What the solution for this?

Upvotes: 0

Views: 12214

Answers (2)

Enigmativity
Enigmativity

Reputation: 117027

I would go about doing it like this:

Dim now = DateTime.Now

Dim data = _
( _
    From line in File.ReadLines(MyFile) _
    Let timestamp = now.Add(TimeSpan.Parse(line.Substring(0, 8))) _
    Let text = String.Join(" ", line.Split().Skip(1)) _
    Select New With { .TimeStamp = timestamp, .Text = text } _
).ToArray()

From my sample data I then get these results:

results

As you can see, the array contains the actual time to display the text and the text itself. It should be fairly easy now to use the timer to compare the current time with the next time stamp and move an index to keep track of the current line to display.

Upvotes: 0

LInsoDeTeh
LInsoDeTeh

Reputation: 160

You should use a loop instead of hard-coding 0, 1, and 2. To stay with your variable names:

Dim Lines = File.ReadAllLines(MyFile)
For Each line In Lines
  Dim splittedLine() As String = line.Split
  'whatever you do with the splitted line
Next

Upvotes: 2

Related Questions