Sabari M Sabari M
Updated date Jan 05, 2021
In this blog, we see how to read a text file using StreamReader in C#. It is very easy to read a text file in C#,  we use StreamReader class is used to read a string from the stream and can be found under System.IO namespace.

This blog shows how to read a text file using StreamReader in C#.  It is very easy to read a text file in C#,  we use StreamReader class is used to read a string from the stream and can be found under System.IO namespace. It gives Read() and ReadLine() methods to read data from the stream.

We need to pass the file location path to File.OpenText() method to open the text file. ReadLine() method is used to read each line in the text file as the stream.

How to read the first line of the text file?

In this example, we read the first line of the text file by using  ReadLine() method.

using System;
using System.IO;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Empty;
            string filePath = @"E:\Employee.txt";

            // Open and Read the file contents
            using (StreamReader streamReader = File.OpenText(filePath))
            {
                Console.WriteLine(streamReader.ReadLine());
            }
        }
    }
}

Output:

John Peter

How to read the whole text file?

In this example, we read all lines of the text file by using while loop and ReadLine() method.

using System;
using System.IO;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Empty;
            string filePath = @"E:\Employee.txt";

            // Open and Read the file contents
            using (StreamReader streamReader = File.OpenText(filePath))
            {
                // read line by line
                while ((str = streamReader.ReadLine()) != null)
                {
                    Console.WriteLine(str);
                }
                Console.ReadKey();
            }
        }
    }
}

Output:

John Peter
Rahul Sharma
Mathew John
Kumar Raja

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!
×