简体   繁体   中英

how to search and display specific line from a text file vb.net

Hi I am trying to search for a line which contains whats the user inputs in a text box and display the whole line. My code below doesnt display a messsagebox after the button has been clicked and i am not sure if the record has been found

   Dim filename, sr As String
    filename = My.Application.Info.DirectoryPath + "\" + "mul.txt"

    Dim file As String()
    Dim i As Integer = 0
    file = IO.File.ReadAllLines(filename)
    Dim found As Boolean
    Dim linecontain As Char

    sr = txtsr.ToString



    For Each line As String In file
        If line.Contains(sr) Then
            found = True
            Exit For
        End If
        i += 1
        If found = True Then
            MsgBox(line(i))
        End If


    Next



End Sub

You should be calling ReadLines here rather than ReadAllLines . The difference is that ReadAllLines reads the entire file contents into an array first, before you can start processing any of it, while ReadLines doesn't read a line until you have processed the previous one. ReadAllLines is good if you want random access to the whole file or you want to process the data multiple times. ReadLines is good if you want to stop processing data when a line satisfies some criterion. If you're looking for a line that contains some text and you have a file with one million lines where the first line matches, ReadAllLines would read all one millions lines whereas ReadLines would only read the first.

So, here's how you display the first line that contains specific text:

For Each line In File.ReadLines(filePath)
    If line.Contains(substring) Then
        MessageBox.Show(line)
        Exit For
    End If
Next

With regards to your original code, your use of i makes no sense. You seem to be using i as a line counter but there's no point because you're using a For Each loop so line contains the line. If you already have the line, why would you need to get the line by index? Also, when you try to display the message, you are using i to index line , which means that you're going to get a single character from the line rather than a single line from the array. If the index of the line is greater than the number of characters in the line then that is going to throw an IndexOutOfRangeException , which I'm guessing is what's happening to you.

This is what comes from writing code without knowing what it actually has to do first. If you had written out an algorithm before writing the code, it would have been obvious that the code didn't implement the algorithm. If you have no algorithm though, you have nothing to compare your code to to make sure that it makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM