Search in file Learn programming C#

Lesson:

Dynamic Memory Management


Exercise:

Search in file 79


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:

using System;
using System.Collections;
using System.IO;
namespace Contains
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader myfile = File.OpenText("text.txt");

            try
            {
                ArrayList list = new ArrayList();
                string line;
                do
                {
                    line = myfile.ReadLine();
                    if (line != null)
                        list.Add(line);
                }
                while (line != null);
                myfile.Close();

                string sentence;
                bool exit = false;

                do
                {
                    Console.Write("Enter word or sentence: ");
                    sentence = Console.ReadLine();

                    if (sentence == "")
                        exit = true;
                    else
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            string sentenceList = (string)list[i];

                            if (sentenceList.Contains(sentence))
                            {
                                Console.WriteLine(sentenceList);
                            }
                        }
                    }
                }
                while (!exit);

            }
            catch (Exception e)
            {
                Console.WriteLine("Error, " + e.Message);
            }
        }
    }
}