ZetCode

Reading text files in C#

last modified July 5, 2023

In this article we show how to read text files in C#.

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 this file.

C# read text file with File.ReadLines

The File.ReadLines returns an IEnumerable<string> of all lines of the file. After finishing the iteration, it closes the file. It is much less resource-hungry than methods which return the whole data as a string or as an array of strings.

Program.cs
using System.Text;

var path = "thermopylae.txt";

var enumLines = File.ReadLines(path, Encoding.UTF8);

foreach (var line in enumLines)
{
    Console.WriteLine(line);
}

In the example, we go through the enumeration of lines in a foreach loop and print the contents line by line.

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.

Note: The File.ReadLines is more efficient than File.ReadAllLines, especially for larger files.
Program.cs
using System.Text;

var path = "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# 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.

Note: The File.ReadAllText method should not be used for large files. It is only suitable for simple solutions.
Program.cs
using System.Text;

var path = "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# 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.Text;

var path = "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 File.OpenRead

There is a File.OpenRead helper method to create a FileStream.

Program.cs
using System.Text;

var path = "thermopylae.txt";

using var fs = File.OpenRead(path);
using var sr = new StreamReader(fs, Encoding.UTF8);

string content = sr.ReadToEnd();

Console.WriteLine(content);

The example creates a FileStream with File.OpenRead, passes the stream to StreamReader and reads the text with ReadToEnd.

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.Text;

var path = "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 with File.OpenText

The File.OpenText method opens an existing UTF-8 encoded text file for reading. It is a helper method to work with StreamReader quickly.

Program.cs
using System.Text;

var path = "thermopylae.txt";

using StreamReader sr = File.OpenText(path);
string content = sr.ReadToEnd();

Console.WriteLine(content);

The example opens a text file with File.OpenText and reads its contents with ReadToEnd.

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.Text;

var path = "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.

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.

Source

File and Stream I/O

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

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.