Reading data from a text file is almost similar to writing data to it. You create a  FileStream pointing to the file to be read. But instead of passing the stream to a  StreamWriter class, we used the  StreamReader class which contains methods for reading data from a file. The following program demonstrates reading of a file. The program will use the text file created in the previous lesson as the source file.

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
 
namespace ReadingFromFile
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
 
    class Program
    {
        static void Main()
        {
            List<Person> persons = new List<Person>();
 
            try
            {
                FileStream fs =
                   new FileStream("sample.txt", FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fs);
 
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    string[] fields = line.Split('#');
                    Person newPerson = new Person();
                    newPerson.FirstName = fields[0];
                    newPerson.LastName = fields[1];
                    newPerson.Age = Convert.ToInt32(fields[2]);
                    persons.Add(newPerson);
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
 
            //Show each person's details
            foreach (Person p in persons)
            {
                Console.WriteLine("Name: {0} {1}\nAge: {2}",
                    p.FirstName, p.LastName, p.Age);
            }
        }
    }
}

Figure 1

Name: John Smith
Age: 21
Name: Mike Roberts 
Age: 31
Name: Garry Mathews
Age: 27

We created a class called Person(line 8-13) to store each person’s data that is retrieved from the file. We also created a List of Personobjects(line  19) the will hold all the person’s data and makes it easier for us to output them.  We will be opening and reading a text file so in lines 23-24, we created a FileStream object with the location of the file to be read, a FileMode value of Open (which means to open the file), and a FileAccess value of Read (which only allows reading of the file).

We created a StreamReader object(line 25) and passed the created stream to its constructor. The StreamReader object will be responsible for reading data to the file. We then enter a  while loop in line 27 and we test if the stream position has not yet reached the end by using the EndOfStream property of the StreamReader class. Inside the loop, we used the ReadLine() method of the StreamReader class which reads the whole line starting from where the stream position is located. The position is then moved to the next line.

The whole line is then stored in a string (line 29). We used the Split() method  in line 30 and passed the character ‘#’ to separate the fields and distribute them to separate elements of the string array. Remember last lesson that we added the ‘#’ character as the delimiter, now you see the reason why we did that. A new Person object was created and each element of the fields array was assigned to the respective properties of the created Person object. The Person object is then added to the persons List. When the end of the file is reached, the loop exits and proceeds to the displaying of each person.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *