Summary: in this tutorial, you’ll learn various techniques to read text files in C# using
, File.ReadAllText
()
, File.ReadAllText
Async()
, File.ReadAllLines
()
method, and File.ReadAllLines
Async()FileStream
class.
C# provides various ways to allow you to read text files effectively. We’ll create a readme.txt
file in the C:\temp\
directory for the demonstration.
The readme.txt
file has two lines:
Hello
Bye
Code language: C# (cs)
Reading a text file into a string
If a text file is small, you can read all the file contents into a string using the
static method:File.ReadAllText
()
public static string ReadAllText(string path);
Code language: C# (cs)
The
method opens a text file, reads all the text of the file into a string, and then closes the file.File.ReadAllText
()
For example, the following program uses the
method to read the contents in the File.ReadAllText
()readme.txt
file and writes the text to the console:
string contents = File.ReadAllText(@"C:\temp\readme.txt");
Console.WriteLine(contents);
Code language: C# (cs)
If the file is not found, the
raises a File.ReadAllText
()
. For example, the following program attempts to read a file FileNotFoundException
readme1.txt
from the C:\temp\
directory, which doesn’t exist and handles the
:FileNotFoundException
try
{
string contents = File.ReadAllText(@"C:\temp\readme1.txt");
Console.WriteLine(contents);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
Code language: C# (cs)
Output:
Could not find file 'C:\temp\readme1.txt'.
Code language: C# (cs)
Reading a text file into an array of string
If you want to process a small text file line by line, you can read its contents into an array of strings, where each array element stores a line in the text file.
To read the contents of a text file into an array of strings, you use the
method:File.ReadAllLines
()
public static string[] ReadAllLines (string path);
Code language: C# (cs)
For example:
string[] lines = File.ReadAllLines(@"C:\temp\readme.txt");
foreach (var line in lines)
{
Console.WriteLine(line.ToUpperInvariant());
}
Code language: C# (cs)
Output:
HELLO
BYE
Code language: C# (cs)
Reading a large text file line by line
If a text file is large, reading the entire text file into a string or an array of strings is not memory-optimized.
In this case, you can read the contents of a text file using a stream and process the contents line by line.
A stream represents a flow of data that you can read from. To read data from a file, you can create a FileStream
and use a StreamReader
to read data from the FileStream
.
Here are the steps:
First, create a
with the FileStream
FileMode
.Open using the
class:FileStream
using var fs = new FileStream(path, FileMode.Open);
Code language: C# (cs)
Second, create a new StreamReader
to read the contents of the FileStream
:
using var reader = new StreamReader(fs);
Code language: C# (cs)
Third, read the line from the
till the end of the stream. To check if the program reaches the end of the stream, you use the StreamReader
reader.EndOfStream
property. To read a line from a
, you use the StreamReader
ReadLine()
method.
The following program demonstrates how to read the contents of the readme.txt
line by line using a FileStream
and StreamReader
:
using static System.Console;
using var fs = new FileStream(@"C:\temp\readme.txt", FileMode.Open);
using var reader = new StreamReader(fs);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
WriteLine(line?.ToUpperInvariant());
}
Code language: C# (cs)
Output:
HELLO
BYE
Code language: C# (cs)
The program works fine but the code looks quite verbose. To make it more concise, you can use the
static method.File.OpenText
()
The
method accepts a path and returns a new instance of the File.OpenText
()StreamReader
class. Here’s the revised version of the above program:
using static System.Console;
using var reader = File.OpenText(@"C:\temp\readme.txt");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
WriteLine(line?.ToUpperInvariant());
}
Code language: C# (cs)
So these two lines:
using var fs = new FileStream(@"C:\temp\readme.txt", FileMode.Open);
using var reader = new StreamReader(fs);
Code language: C# (cs)
become one:
using var reader = File.OpenText(@"C:\temp\readme.txt");
Code language: C# (cs)
Read all text into a string asynchronously
To read all contents of a text file into a string asynchronously, you use the
method:File.ReadAllTextAsync
()
public static Task<string> ReadAllTextAsync (
string path,
CancellationToken cancellationToken = default
);
Code language: C# (cs)
For example:
using static System.Console;
var text = await File.ReadAllTextAsync(@"C:\temp\readme.txt");
WriteLine(text);
Code language: C# (cs)
Output:
Hello
Bye
Code language: C# (cs)
Since the
method returns a File.ReadAllTextAsync
()Task<String>
, you need to use await
keyword to wait for the task to complete and get the string result.
Similarly, you can read all lines of a text file into an array of strings asynchronously using the
static method:File.ReadAllLineAsync
()
public static Task<string[]> ReadAllLinesAsync (
string path,
CancellationToken cancellationToken = default
);
Code language: C# (cs)
For example:
using static System.Console;
var lines = await File.ReadAllLinesAsync(@"C:\temp\readme.txt");
foreach (var line in lines)
{
WriteLine(line);
}
Code language: C# (cs)
Reading a text file with a specified encoding
By default, each of the ReadAllText
, ReadAllLines
, ReadAllTextAsync
, and ReadAllLineAsync
method has an overload that allows you to specify the encoding applied to the text of the file:
public static string ReadAllText (string path, Encoding encoding);
public static string[] ReadAllLines (string path, Encoding encoding);
public static Task<string> ReadAllTextAsync (string path, Encoding encoding, CancellationToken cancellationToken = default);
public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default);
Code language: C# (cs)
In this syntax, the Encoding
class belongs to the System.Text
namespace.
Summary
- Use the
method to read the contents of a small text file into a string.File.ReadAllText
() - Use the
method to read the contents of a small text file into an array of strings.File.ReadAllLines
() - Use the
method to read the contents of a small text file into a string asynchronously.File.ReadAllTextAsync
() - Use the
method to read all lines of a text file into an array of strings asynchronously.File.ReadAllLinesAsync
()