0

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

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

这是我现在使用的代码。

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
4

2 回答 2

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
于 2013-07-16T12:28:27.183 回答
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

这段代码可能对您有所帮助

于 2013-07-16T12:17:25.943 回答