Loop through the lines of a text file in VB.NET

烈酒焚心 提交于 2019-12-29 08:01:40

问题


I have a text file with some lines of text in it.

I want to loop through each line until an item that I want is found*, then display it on the screen, in the form of a label.

*I am searching for the item through a textbox.

That is, in sudo:

For i = 0 To number of lines in text file
    If txtsearch.text = row(i).text Then
        lbl1.text = row(i).text
Next i

回答1:


You can use the File.ReadLines Method in order to iterate throughout your file, one line at a time. Here is a simple example:

    Dim Term As String = "Your term"
    For Each Line As String In File.ReadLines("Your file path")
        If Line.Contains(Term) = True Then
            ' Do something...Print the line
            Exit For
        End If
    Next



回答2:


Here's a function that will spit back your string from the row that contains your search term...

  Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
    Dim sr As StreamReader = New StreamReader(strFilePath)
    Dim strLine As String = String.Empty

    Try
        Do While sr.Peek() >= 0
            strLine = String.Empty
            strLine = sr.ReadLine
            If strLine.Contains(strSearchTerm) Then
                sr.Close()
                Exit Do
            End If
        Loop

        Return strLine
    Catch ex As Exception
        Return String.Empty
    End Try
  End Function

To use the function you can do this...

 Dim strText As String = SearchFile(FileName, SearchTerm)
 If strText <> String.Empty Then
   Label1.Text = strText
 End If



回答3:


LOOPING AND GETTING ALL XML FILES FROM DIRECTORY IF WE WANT TEXTFILES PUT "*.txt" IN THE PLACE OF "*xml"

Dim Directory As New IO.DirectoryInfo(Path)

    Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.xml")
    allFiles = allFiles.OrderByDescending(Function(x) x.FullName).ToArray()
    Dim singleFile As IO.FileInfo


    For Each singleFile In allFiles
        'ds.ReadXml(singleFile)
        xd.Load(singleFile.FullName)

        Dim nodes As XmlNodeList = xd.DocumentElement.SelectNodes("/ORDER/ORDER_HEADER")
        Dim ORDER_NO As String = " "
        For Each node As XmlNode In nodes
            If Not node.SelectSingleNode("ORDER_NO") Is Nothing Then
                ORDER_NO = node.SelectSingleNode("ORDER_NO").InnerText
            End If
        Next

    Next


来源:https://stackoverflow.com/questions/25731772/loop-through-the-lines-of-a-text-file-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!