Pure vb noob ..我正在尝试在找到时读取和写入数据。我使用以下代码来获取文件。我现在可以将文件放到列表框中,但是真的需要查找文件,搜索特定单词并复制该数据。
For Each foundfile As String In Directory.GetFiles("C:\tmp\logsd", "*.log", SearchOption.AllDirectories)
If foundfile.Contains("un") Then
ListBox1.Items.Add(foundfile)
End If
Next
找到所有文件后,我需要搜索所有这些文本文件并查找特定单词。
与此相似的文本文件
19-Jan-2015 22:50:52.425 Green:1 Red:-1 Apples:1 Blue:2 Yellow:2
20-Jan-2015 22:50:52.425 Green:1 Red:-1 Pears:1 Blue:2 Yellow:2
20-Jan-2015 22:50:52.425 Green:1 Red:-1 Apples:1 Blue:2 Yellow:2
因此,如果我在哪里搜索苹果,它会找到2个实例并将所有这些行复制到文本文件中。
19-Jan-2015 22:50:52.425 Green:1 Red:-1 Apples:1 Blue:2 Yellow:2
20-Jan-2015 22:50:52.425 Green:1 Red:-1 Apples:1 Blue:2 Yellow:2
我厌倦了使用streamreader,但我似乎只能显示一行。
Using reader As New StreamReader(ListBox1.SelectedItem.ToString)
While Not reader.EndOfStream
Dim line As String = reader.ReadToEnd()
If line.Contains("Apples") Then
'????????
Exit While
End If
End While
End Using
答案 0 :(得分:0)
在经历了一些乱七八糟的事情后,我得到了我想做的事情,但这似乎是一种非常糟糕的做法。
ListBox2.Items.Clear()
Dim LineCounter As Integer = 0
Using reader As New StreamReader(ListBox1.SelectedItem.ToString)
While Not reader.EndOfStream
Dim lines As String() = File.ReadAllLines(ListBox1.SelectedItem.ToString)
Dim line As String = reader.ReadLine()
LineCounter = LineCounter + 1
If line = "apples:1" Then
ListBox2.Items.Add(lines(LineCounter - 4))
ListBox2.Items.Add(lines(LineCounter - 3))
ListBox2.Items.Add(lines(LineCounter - 2))
ListBox2.Items.Add(lines(LineCounter - 1))
ListBox2.Items.Add(lines(LineCounter))
ListBox2.Items.Add(lines(LineCounter + 1))
ListBox2.Items.Add(lines(LineCounter + 2))
ListBox2.Items.Add(lines(LineCounter + 3))
ListBox2.Items.Add(lines(LineCounter + 4))
ListBox2.Items.Add(lines(LineCounter + 5))
ListBox2.Items.Add(lines(LineCounter + 6))
ListBox2.Items.Add(lines(LineCounter + 7))
ListBox2.Items.Add(lines(LineCounter + 8))
ListBox2.Items.Add(lines(LineCounter + 9))
ListBox2.Items.Add(lines(LineCounter + 10))
ListBox2.Items.Add(lines(LineCounter + 11))
ListBox2.Items.Add(" ")
End If
End While
End Using