Home Programs Read the Contents of a File in C#

Read the Contents of a File in C#

In this example we will read the contents of a file in C#

Example

The ‘StreamReader’ is used to position the file pointer at the beginning of the file.

We then use BaseStream.Seek() function  to read until the end of the file is encountered.

Using a while loop we check that the value of ‘str’ variable is not equal to null. If the condition is true, then the loop is iterated.

The ReadLine() function is then used to read the content in the file and once this is complete we close the writer and file.

using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("testfile.txt", FileMode.Open, FileAccess.Read);
            //Position the File Pointer at the Beginning of the File
            StreamReader sr = new StreamReader(fs);
            //Read till the End of the File is Encountered
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            string str = sr.ReadLine();
            while (str != null)
            {
                Console.WriteLine("{0}", str);
                str = sr.ReadLine();
            }
            //Close the Writer and File
            sr.Close();
            fs.Close();
            Console.Read();
        }
    }
}

Based on the contents of the file, this is what was seen in the console window

This is my test file with some test text in it
Another line of text
1234560912
maxchsarp.com

You may also like