How : To Read A Text File In C# - Trickcode

Reading data from a text file,FileStream ,StreamWriter , How : To Read A Text File In C#
Share it:



Read A Text File In C#

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 a method to read data from a file. The following program demonstrates the reading of the 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 persons = new List();
 
             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);
              }
        }
       }
   }

Output:

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 Person objects(line 19) the will hold all the person’s data and makes it easier for us to output them. 

It 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 reading (which only allows reading of the file). 

We can create 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 inline 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. 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 the 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 person List. When the end of file is reached, the loop exits and proceeds to the displaying of each person.

Share it:

C#

How To Read A Text File In C#

Post A Comment:

0 comments: