TechieClues TechieClues
Updated date Nov 17, 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

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

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