Search in file Learn programming Visual Basic (VB.net)

Lesson:

Dynamic Memory Management


Exercise:

Search in file 53


Objetive:

Create a program to read a text file and ask the user for sentences to search in it.

It will read the whole file, store it in an ArrayList, ask the user for a word (or sentence) and display all the lines that contain such word. Then it will ask for another word and so on, until the user enters an empty string.


Code:

Imports System
Imports System.Collections
Imports System.IO
Namespace Contains
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim myfile As StreamReader = File.OpenText("text.txt")

            Try
                Dim list As ArrayList = New ArrayList()
                Dim line As String

                Do
                    line = myfile.ReadLine()
                    If line IsNot Nothing Then list.Add(line)
                Loop While line IsNot Nothing

                myfile.Close()
                Dim sentence As String
                Dim [exit] As Boolean = False

                Do
                    Console.Write("Enter word or sentence: ")
                    sentence = Console.ReadLine()

                    If sentence = "" Then
                        [exit] = True
                    Else

                        For i As Integer = 0 To list.Count - 1
                            Dim sentenceList As String = CStr(list(i))

                            If sentenceList.Contains(sentence) Then
                                Console.WriteLine(sentenceList)
                            End If
                        Next
                    End If
                Loop While Not [exit]

            Catch e As Exception
                Console.WriteLine("Error, " & e.Message)
            End Try
        End Sub
    End Class
End Namespace