Home > OS >  Find word in a txt file and read previous line VB.NET
Find word in a txt file and read previous line VB.NET

Time:02-24

I am reading a txt file line by line in VB to look for the word "unable". That much works. The code is here:

Imports System
Imports System.IO
Imports PartMountCollector.HandMount_WebReference
Imports System.Threadingtime
Imports eCenter.Motor.VBConnect

Module Program
    Sub Main(args As String())
        Dim unUpdate As String = "Unable"
        Dim time = DateTime.Now
        Dim yesterday = time.AddDays(-1)
        Dim format As String = "yyyyMMdd"
        Dim words As String()

        For Each Line As String In File.ReadLines("C:\Users\te-smtinternal\Desktop\ReStockLog\"   time.ToString(format)   ".txt")
            words = Split(Line)
            If Line.Contains(unUpdate) = True Then
                Console.WriteLine("Exist")
                'Read previous line looking for "Success"'
            End If
            Console.WriteLine("not found")
        Next
    End Sub
End Module

Now I need be able to identify this line and read the previous line, looking for the word "success".

Any help would be appreciated

CodePudding user response:

You just need to declare a variable outside of the loop to store the previous line. Here I've named it previousLine...

Const unUpdate As String = "Unable"
Dim time = DateTime.Now
Const format As String = "yyyyMMdd"

Dim previousLine as String = Nothing
For Each currentLine As String In File.ReadLines("C:\Users\te-smtinternal\Desktop\ReStockLog\"   time.ToString(format)   ".txt")
    If currentLine.Contains(unUpdate) Then
        Console.WriteLine("Exist")

        If previousLine Is Nothing Then
            ' The very first line of input contains unUpdate
        Else If previousLine.Contains("Success")
            ' A line after the first line of input contains unUpdate
        End If
    Else
        Console.WriteLine("not found")
    End If

    previousLine = currentLine
Next

At the end of each loop iteration the currentLine becomes the previousLine and, if there is another iteration, it will read a new value for currentLine.

Also note that in...

If Line.Contains(unUpdate) = True Then

...you don't need the = True comparison because Contains() already returns a Boolean.

CodePudding user response:

Instead of trying to handle each line one at a time, you could read all the lines and then iterate through them which would give you access to the previous line, like:

Dim lines = IO.File.ReadAllLines(file_name)
dim previous_line as string = ""

for x as integer = 0 to lines.count-1
  if lines(x).ToString.Contains("unable") then previous_line = lines(x-1).ToString
next

of course you would need to handle the exception of finding a hit on the first line which would throw an out of index error. So you would simply need to add a check to make sure x > 0.

  • Related