简体   繁体   English

读取一行中的字符串,然后使用VB.NET在文本文件中显示下一行

[英]Read the string within a line and then display the next line in a text file using VB.NET

Using VB.Net and a text file 使用VB.Net和文本文件

For Example #1: 10 LINES (Below are the text/data inside a text file) 对于示例 1:10行(以下是文本文件中的文本/数据)
Filename: Test1.txt 文件名:Test1.txt
Note #1: I want to search the string "F1" then display the "I play Farmville" in a TextBox1.Text 注意#1:我想搜索字符串“ F1”,然后在TextBox1.Text中显示“ I play Farmville”

FaceF1book 'line#1 FaceF1book'line#1
I play Farmville 'line#2 我玩Farmville'line#2
'line#3 '第3行
'line#4 '第4行
TwitF2ter 'line#5 TwitF2ter'line#5
Occassionally use this site 'line#6 偶尔使用此网站的“第6行”
'line#7 '第7行
'line#8 '第8行
FriendsF3ter 'line#9 FriendsF3ter'line#9
I don't want to use this site 'line#10 我不想使用此网站的“第10行”





For Example #2: 12 LINES (Below are the text/data inside a text file) 例如 2:12行(以下是文本文件中的文本/数据)
Filename: Test2.txt 文件名:Test2.txt
Note #2.1: I want to search the string "F2" then display the "Occassionally use this site" in a TextBox1.Text 注意#2.1:我想搜索字符串“ F2”,然后在TextBox1.Text中显示“偶尔使用此站点”
Note #2.2: You can notice that the line position of the data aren't the same in the Example #1 注意#2.2:您可能会注意到示例1中数据的行位置不同

FaceF1book 'line#1 FaceF1book'line#1
I play Farmville 'line#2 我玩Farmville'line#2
I love to chat with my friends 'line#3 我喜欢和我的朋友在第3行聊天
I want to be famous 'line#4 我想成为著名的'第4行
'line#5 '第5行
'line#6 '第6行
TwitF2ter 'line#7 TwitF2ter'第7行
Occassionally use this site 'line#8 偶尔使用此网站的“第8行”
'line#9 '第9行
'line#10 '第10行
FriendsF3ter 'line#11 FriendsF3ter'line#11
I don't want to use this site 'line#12 我不想使用此网站的“第12行”

Here's another approach: 这是另一种方法:

    Dim dataFile As String = System.IO.File.ReadAllText("C:\Users\WindowsUser\Desktop\Test Files\test1.txt")
    If System.IO.File.Exists(dataFile) Then
        Try
            Dim lines As New List(Of String)
            lines.AddRange(System.IO.File.ReadAllLines(dataFile))

            Dim searchFor As String = "F1"
            For i As Integer = 0 To lines.Count - 1
                If lines(i).Contains(searchFor) Then
                    ' ... do something with lines(i + 1) ... ?
                    Exit For
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Error Reading File")
        End Try
    Else
        MessageBox.Show(dataFile, "File Not Found")
    End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM