【问题标题】:Read the string within a line and then display the next line in a text file using VB.NET读取一行中的字符串,然后使用 VB.NET 在文本文件中显示下一行
【发布时间】:2013-10-03 02:49:21
【问题描述】:

使用 VB.Net 和文本文件

例如 #1: 10 行(以下是文本文件中的文本/数据)
文件名:Test1.txt
注意 #1:我想搜索字符串“F1”,然后在 TextBox1.Text 中显示“我玩 Farmville”

FaceF1book 'line#1
我玩 Farmville 'line#2
'第 3 行
'行#4
TwitF2ter 'line#5
偶尔使用这个网站'line#6
'第7行
'行#8
FriendsF3ter 'line#9
我不想使用此站点 'line#10





例如 #2: 12 行(以下是文本文件中的文本/数据)
文件名:Test2.txt
注意 #2.1:我想搜索字符串“F2”,然后在 TextBox1.Text
中显示“偶尔使用此站点” 注意 #2.2:您可以注意到示例 #1 中数据的行位置不同

FaceF1book 'line#1
我玩 Farmville 'line#2
我喜欢和我的朋友聊天'line#3
我想出名'line#4
'行#5
'第 6 行
TwitF2ter 'line#7
偶尔使用这个网站'line#8
'行#9
'行#10
FriendsF3ter 'line#11
我不想使用这个网站 'line#12

【问题讨论】:

  • 在 tF3ere someF1where 中有问题吗?
  • @Plutonix:让我们考虑 F1、F2 和 F3 是文本文件中不可更改的数据,其余部分可能是替换/更改...您可以在我的 2 个示例中注意到相同的数据,但是另一个包含更多数据...我需要在一行中搜索特定字符串(假设第一行包含我想要的字符串),而是显示第一行我想显示第二行或第三行.. .

标签: vb.net text


【解决方案1】:

这是另一种方法:

    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

【讨论】:

  • 我正在寻找一个获取文本文件中每一行的行位置的代码。我将搜索一个字符串...假设该字符串可以在文本的第三行中找到然后文件而不是显示包含字符串的整个第三行...我想显示整个第四行和/或第五行和/或六行...
  • 感谢您的回复。我试图将您的代码插入到我的代码中,但遇到了错误。错误消息:路径中有非法字符。您的代码“lines.AddRange(System.IO.File.ReadAllLines(dataFile))”中的错误。
  • 您是否更改了dataFile 中的路径以反映文件的正确路径?错误表示里面的值无效...
  • 是的,我已经这样做了。这是我的路径“C:\Users\WindowsUser\Desktop\Test Files\test1.txt”
  • 看起来不错。我想。尝试编辑后的代码,看看它是否有助于查明问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 2021-05-06
  • 2013-11-04
相关资源
最近更新 更多