获取文件中的数据字符串,循环直到找到所有实例

时间:2013-07-16 12:00:57

标签: vb.net loops streamreader

我有一些vb.net代码会搜索字符串,然后在其后面获取一定数量的字符并显示在文本框中。

我的问题是,在某些情况下,我需要显示多个文本字符串,因此,如果只搜索“name”一次,如何遍历文件并显示所有实例的列表?< / p>

这是我现在使用的代码。

Public Sub readAddress()

    Dim sr As StreamReader = New StreamReader(profile + "\Desktop\" + dir + "\" + newfile + ".dat")
    Dim data = sr.ReadToEnd()
    Dim pos = data.IndexOf("name")
    If pos >= 0 Then
        ListBox1.Text = data.Substring(pos, 39).Replace("name""", "") + Environment.NewLine
    End If
    sr.Close()
    txt()
End Sub

2 个答案:

答案 0 :(得分:0)

Dim FILE_NAME As String = sr
Dim TextLine As String
If System.IO.File.Exists( FILE_NAME ) = True Then
    Dim objReader As New System.IO.StreamReader(FILE_NAME)
    Do While objReader.Peek() <> -1
        TextLine = TextLine & objReader.ReadLine() & vbNewLine
    Loop
    ListBox1.Text = TextLine
Else
    MsgBox("File Does Not Exist")
End If

这段编码可能对你有帮助

答案 1 :(得分:0)

考虑使用正则表达式:

Imports System.Text.RegularExpressions

Public Sub readAddress()
    Dim fileText = File.ReadAllText(profile + "\Desktop\" + dir + "\" + newfile + ".dat")
    Dim matches = Regex.Matches(fileText,"name")

    For Each m In matches
        'The call to Substring will return 10 characters after each instance of "name"
        Listbox1.Text += Environment.NewLine & fileText.Substring(m.Index + 4,10)
    Next

    'Instead of the For Each loop, use LINQ, and String.Join
    Listbox1.Text = String.Join(Environment.NewLine, matches.Select(Function(m) fileText.Substring(m.Index + 4,10)))
End Sub