Loop through lines of text file in VB.NET

I have a text file with some lines of text.

I want to loop through each line until I find the element I want * and then display it on the screen as a label.

* I am looking for an element via a text box.

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

      

+3


source to share


3 answers


You can use the File.ReadLines Method to iterate over the entire file, one line at a time. Here's 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

      

+5


source


Here's a function that will return your string from the string containing 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 this feature, you can do this ...

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

      

+3


source


DISCONNECTING AND GETTING ALL XML FILES FROM THE DIRECTORY IF WE WANT TEXTFILES Insert "* .txt" IN PLACE "* 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

      

0


source







All Articles