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

后端 未结 3 1986
猫巷女王i
猫巷女王i 2020-12-19 21:37

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

3条回答
  •  执笔经年
    2020-12-19 22:00

    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
    

提交回复
热议问题