Search in file Learn programming C#



Lesson:

Dynamic Memory Management


Exercise:

Search in file


Objetive:

Create a program that reads a text file, saves its content to an ArrayList, and asks the user to enter sentences to search within the file.

The program should ask the user to enter a word or sentence and display all the lines that contain the word or sentence. It should then prompt the user to enter another word or sentence and repeat the process 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);
            }
        }
    }
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.