Search code examples
vb.nettext-filesstreamreaderreadlinespeek

vb.net - r.peek()>=0 line = r.readline()


I am using vb.net to read a text file and see if a record matched, and to pick out that record and write it to excel.

However with the peek loop it reads the file until the end of it. I have 2 peek loop - the outer peek loop looks for the item, the inner loop search to find it.

Can the peek loop stop, and continue where the outer loop stop ? This is an example of my code. I did a for loop outside both search loop to continue where the outer loop stops however is not right that way either. Thanks

 For i = 1 To t_idex

            rder.BaseStream.Seek(0, IO.SeekOrigin.Begin)
            rder.DiscardBufferedData()

            Do While rder.Peek() >= 0
                line = rder.ReadLine()
                r_idx += 1
                st_outer += 1

                m = Mid(line, 3, 7)
                P = Mid(line, 19, 7)
                b= Trim(Mid(line, 34, 14))

                If Len(b) = 14 Then
                    Do While rder.Peek() >= 0
                        line2 = rder.ReadLine()

                        m2 = Mid(line2, 3, 7)
                        P2 = Mid(line2, 19, 7)
                        b2 = Trim(Mid(line2, 34, 14))

                        If b = b2 Then
                            cnt_dups += 1

                        End If

                        r_idx += 1
                    Loop
                End If
                i = st_outer
            Loop

        Next

Solution

  • See what this does for you....

    Dim Lines() As String = File.ReadAllLines("SomeTextFile.txt")
    
    For LineIndex = 0 To Lines.GetUpperBound(0)
        Dim Match1 As String = Mid(Lines(LineIndex).Trim, 34, 14)
        If Match1.Length = 14 Then
            For Each RemainingLine As String In Lines.Skip(LineIndex + 1)
                Dim Match2 As String = Mid(RemainingLine.Trim, 34, 14)
                If Match1 = Match2 Then
                    ' We have a duplicate...
                    DoSomething()
    
                    ' Resume outer loop
                    ' Comment this line to find all duplicates
                    ' Uncomment this line to short-circuit exit upon finding
                    '     the first duplicate
                    Exit For
                End If
            Next
        End If
    Next
    

    References: