Ebooks

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.

C# stream

Stream provides 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.

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. 

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

C# read text 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.

Program.cs
using System;
using System.IO;
using System.Text;

namespace ReadAllText
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            string content = File.ReadAllText(path, Encoding.UTF8);
            Console.WriteLine(content);
        }
    }
}

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

C# read text 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.

Program.cs
using System;
using System.IO;
using System.Text;

namespace ReadAllLines
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            string[] lines = File.ReadAllLines(path, 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.

C# reading text 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.

Program.cs
using System;
using System.IO;
using System.Text;

namespace StreamReaderReadToEnd
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            using var sr = new StreamReader(fs, Encoding.UTF8);
            
            string content = sr.ReadToEnd();

            Console.WriteLine(content);
        }
    }
}

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

using var fs = new FileStream(path, 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 var sr = new StreamReader(fs, Encoding.UTF8);

The FileStream is passed to the StreamReader.

string content = sr.ReadToEnd();

StreamReader's 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.

Program.cs
using System;
using System.IO;
using System.Text;

namespace StreamReaderReadLine
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            using var sr = new StreamReader(fs, Encoding.UTF8);

            string line = String.Empty;

            while ((line = sr.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.

C# read text 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.

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

namespace ReadTextFileAsync
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var path = @"C:\Users\Jano\Documents\thermopylae.txt";

            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            using var sr = new StreamReader(fs, Encoding.UTF8);

            string content = await sr.ReadToEndAsync();
            Console.WriteLine(content);
        }
    }
}

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

static async Task Main(string[] args)

The async modifier allows asynchronous operations in the Main() method.

string content = await sr.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.