[英]Find word in a txt file and read previous line VB.NET
我正在 VB 中逐行读取 txt 文件以查找“无法”一词。 这么多工作。 代码在这里:
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
现在我需要能够识别这一行并阅读上一行,寻找“成功”一词。
任何帮助,将不胜感激
您只需要在循环外声明一个变量来存储上一行。 在这里,我将其命名为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
在每次循环迭代结束时, currentLine
变为previousLine
,如果有另一次迭代,它将读取currentLine
的新值。
另请注意,在...
If Line.Contains(unUpdate) = True Then
...您不需要= True
比较,因为Contains()
已经返回Boolean
。
您可以读取所有行,然后遍历它们,而不是尝试一次处理每一行,这样您就可以访问上一行,例如:
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
当然,您需要处理在第一行找到匹配项的异常,这会抛出索引错误。 所以你只需要添加一个检查来确保 x > 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.