Reading text files in C#

In this article we show how to read text files in C#. C# tutorial is a comprehensive tutorial on C# language.

Input & output in C# is based on streams. A Stream is an abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket.

The Stream class and its derived classes provide a generic interface to the types of input and output, and isolate the programmer from the specific details of the operating system and the underlying devices. For instance, MemoryStream works with data located in the memory and FileStream with data in a files.

In our examples, we are going to read from the following file:

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states, 
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 
course of three days, during the second Persian invasion of Greece. 

The file is located in current working directory.

Reading a file with File.ReadAllText

The File.ReadAllText() method opens a text file, reads all lines of the file into a string, and then closes the file.

ReadTextFileEx.cs
using System;
using System.IO;
using System.Text;

public class ReadTextFileEx
{
    static void Main()
    {
        string content = File.ReadAllText("thermopylae.txt", Encoding.UTF8);

        Console.WriteLine(content);
    }
}

The example reads the contents of the thermopylae.txt file and prints them to the console.

Reading a file with File.ReadAllLines

The File.ReadAllLines() opens a text file, reads all lines of the file into a string array, and then closes the file.

ReadTextFileEx2.cs
using System;
using System.IO;
using System.Text;

public class ReadTextFileEx2
{
    static void Main()
    {
        string[] lines = File.ReadAllLines("thermopylae.txt", Encoding.UTF8);

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

The contents of the thermopylae.txt file are read and printed to the console using the File.ReadAllLines() method.

foreach (string line in lines) {

    Console.WriteLine(line);
}

We loop over the array and print its elements.

Reading a file with StreamReader

StreamReader is designed for character input in a particular encoding. It is used for reading lines of information from a standard text file.

Using StreamReader's ReadToEnd

The ReadToEnd() method reads all characters from the current position of the stream to its end.

ReadTextFileEx3.cs
using System;
using System.IO;
using System.Text;

public class ReadTextFileEx3
{
    static void Main()
    {    
        string content = String.Empty;;
        
        FileStream fs = new FileStream("thermopylae.txt", FileMode.Open, 
                FileAccess.Read);
        
        using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
        {
            content = streamReader.ReadToEnd();
        }

        Console.WriteLine(content);
    }
}

The example reads a file with the StreamReader's ReadToEnd() method.

FileStream fs = new FileStream("thermopylae.txt", FileMode.Open, FileAccess.Read);

The FileStream class provides a Stream for a file, supporting both synchronous and asynchronous read and write operations. The constructor initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
{
    content = streamReader.ReadToEnd();
}

The FileStream is passed to the StreamReader. Its ReadToEnd() method reads all characters from the current position to the end of the file.

Using StreamReader's ReadLine

The ReadLine() method of the StreamReader reads a line of characters from the current stream and returns the data as a string.

ReadTextFileEx4.cs
using System;
using System.IO;
using System.Text;

public class ReadTextFileEx4
{
    static void Main()
    {    
        FileStream fs = new FileStream("thermopylae.txt", FileMode.Open, 
                FileAccess.Read);
        
        using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
        {
            string line = String.Empty;
            while ((line = streamReader.ReadLine()) != null)
            {
                 Console.WriteLine(line);
            }
        }
    }
}

The code example reads a file line by line.

string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
        Console.WriteLine(line);
}

In a while loop, we read the contents of the file line by line with the StreamReader's ReadLine() method.

Reading a file asynchronously with StreamReader's ReadToEndAsync

The ReadToEndAsync() method reads all characters from the current position to the end of the stream asynchronously and returns them as one string.

ReadTextFileAsync.cs
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public class ReadTextFileAsync
{
    static void Main()
    {    
        Task task = new Task(ReadMyFile);
        task.Start();
        
        Console.ReadLine();
    }
    
    static async void ReadMyFile() {
    
        FileStream fs = new FileStream("thermopylae.txt", 
                FileMode.Open, FileAccess.Read);
        
        using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
        {
            string text = await reader.ReadToEndAsync();
            Console.WriteLine(text);
        }    
    }
}

In the next example, we read a text file asynchronously.

Task task = new Task(ReadMyFile);
task.Start();

A Task class represents an asynchronous operation.

string text = await reader.ReadToEndAsync();

The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task finishes.

In this article, we have read text files in various ways in C#.

You might also be interested in the following related tutorials: MySQL C# tutorial, Date and time in C# Reading a web page in C#, or C# Winforms tutorial.