Nick
Nick

Reputation: 155

VB.net Read Specific Lines From a Text File That Start With and Stop Reading When Start With

I'm looking to read lines from a text file that start with certain characters and stop when the line starts with other characters. So in my example I would like to start reading at line AB and stop at line EF however not all lines will contain the CD line. There will always be a AB line and EF line, however the number of lines in between is unknown.

Here is an example of the lines in a text file I would be reading. You can see that this will create two rows in the DataGridView however the first row is missing the CD line and should be blank.

AB-id1
EF-address1
AB-id2
CD-name1
EF-address2

Here is the code I have so far:

  Dim lines() As String = File.ReadAllLines(textfile)
    For i As Integer = 0 To lines.Length - 1
            If lines(i).StartsWith("AB") Then
            Dim nextLines As String() = lines.Skip(i + 1).ToArray
            
            Dim info As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("CD"))
            Dim name As String = "Yes"
            
            Dim info2 As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("EF"))
            Dim address As String = "Yes"
            End If

            DataGridView.Rows.Add(name,address)
    Next 

Now the output I currently get is:

|Yes|Yes|
|Yes|Yes|

And I should be getting:

||Yes|
|Yes|Yes|

It looks like it's reading too far down the text file and I need it to stop reading at EF. I've tried Do while and Do Until with no success. Any suggestions?

Upvotes: 1

Views: 968

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

You could use the Array.FindIndex function to get the index of the next line starting with your prefix. This way you don't have to skip lines and create a new array each time.

Try this out instead:

Dim lines() As String = File.ReadAllLines(textFile)
For i As Integer = 0 To lines.Length - 1
    If lines(i).StartsWith("AB") Then
        Dim addressIndex As Integer = Array.FindIndex(lines, i + 1, Function(Line) Line.StartsWith("EF"))
        Dim address As String = If(addressIndex <> -1, lines(addressIndex).Substring(3), "") ' Get everything past the "-"

        Dim name As String = ""
        If addressIndex <> -1 Then
            Dim nameIndex As Integer = Array.FindIndex(lines, i + 1, addressIndex - i, Function(line) line.StartsWith("CD"))
            If nameIndex <> -1 Then
                name = lines(nameIndex).Substring(3) ' Get everything past the "-"
            End If
        End If

        DataGridView.Rows.Add(name, address)
    End If
Next

Upvotes: 1

Related Questions