Open a text file and read line by line in C#

Open a text file and read line by line in C#

There are several ways to open a text file and read line by line in c# programming language. 

File.ReadLines(): Simple and efficient

Use File.ReadLines() from System.IO. It streams the file instead of loading everything into memory:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        foreach (string line in File.ReadLines("file.txt"))
        {
            Console.WriteLine(line);
        }
    }
}

Why this is good:

• Memory efficient (great for large files)
• Clean and concise

Using StreamReader (more control)

If you need finer control (encoding, error handling, etc.), use StreamReader:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamReader reader = new StreamReader("file.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Read all lines at once (not for large files)

string[] lines = File.ReadAllLines("file.txt");

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Warning: This loads the entire file into memory—fine for small files, risky for large ones.

Bonus: Async version (for responsiveness)

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using (StreamReader reader = new StreamReader("file.txt"))
        {
            string line;
            while ((line = await reader.ReadLineAsync()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Reading From File with StreamReader in C#

using (StreamReader sr = File.OpenText("path"))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

It is also possible to use TextReader to read a file line by line in C#.

TextReader tr = new StreamReader("path");
Console.WriteLine(tr.ReadLine());
tr.Close();

Reading a text file into String Array in C#

Another method for reading a text file line by line is to use File.ReadAllLines method. If your file is small enough or if you want to access these lines multiple times, then you might load all the lines into memory and re-use them as given below:

string[] lines = File.ReadAllLines("path");
foreach (string line in lines)
{
    if (line.Length > 80)
    {
        Console.WriteLine(line);
    }
}

Contents related to 'Open a text file and read line by line in C#'

C# File Operations, C# Input Output (C# I/O)
C# File Operations, C# Input Output (C# I/O)
How to Open and Read From Excel File in C#
How to Open and Read From Excel File in C#