C# provides several ways to read text files. Use File.ReadAllText() when you need the entire file as one string, and use StreamReader or File.ReadLines() when you want to process the file one line at a time.
C# Read an Entire Text File with File.ReadAllText()
To read the complete contents of a text file into a string, follow these steps.
- Import
System.IOto access theFileclass. - Import
System.Textwhen you need to specify a character encoding. - Call
File.ReadAllText()with the path of the text file and, optionally, an encoding. - Store the returned file content in a
string.
File.ReadAllText() opens the file, reads all its text, and closes the file. This approach is convenient for configuration files, templates, logs, and other files that are small enough to fit comfortably in memory.
Program.cs
using System.IO;
using System.Text;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string textFileContent = File.ReadAllText(@"D:\sample.txt",Encoding.UTF8);
System.Console.WriteLine(textFileContent);
}
}
}
The verbatim string literal @"D:\sample.txt" allows the Windows path to be written without escaping each backslash. The Encoding.UTF8 argument tells C# to decode the file as UTF-8 text.
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
This is C# Tutorial from www.tutorialkart.com.
This is a sample text file.
C# Read a Text File Line by Line with StreamReader
Use StreamReader.ReadLine() when each line should be processed separately or when loading the entire file into memory is unnecessary.
- Import
System.IOforFileStreamandStreamReader. - Import
System.Textto accessEncoding.UTF8. - Open the text file with
FileStreamin read mode. - Create a
StreamReaderfor the file stream. - Call
ReadLine()repeatedly until it returnsnull. - Place the reader in a
usingstatement so the stream is disposed after reading.
Reading a file line by line is useful for large files because the program handles one line at a time instead of storing the complete file content in a single string.
Program.cs
using System.IO;
using System.Text;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
var fileStream = new FileStream(@"d:\sample.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {
string line;
while ((line = streamReader.ReadLine()) != null) {
System.Console.WriteLine("- "+line);
}
}
}
}
}
Each call to ReadLine() returns the next line without its line-ending characters. When the reader reaches the end of the file, the method returns null and the loop stops.
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
- This is C# Tutorial from www.tutorialkart.com.
- This is a sample text file.
C# Read File Lines with File.ReadLines()
File.ReadLines() provides a shorter way to process a text file line by line. It returns an enumerable sequence and reads lines as the loop requests them.
using System;
using System.IO;
class Program
{
static void Main()
{
foreach (string line in File.ReadLines(@"D:\sample.txt"))
{
Console.WriteLine(line);
}
}
}
This method is suitable when you only need to iterate through the lines. Use File.ReadAllLines() instead when you specifically need every line stored in a string[].
Read a Text File Asynchronously in C#
Applications that should remain responsive while file input is in progress can use File.ReadAllTextAsync(). The method returns a task that completes with the file content.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string content = await File.ReadAllTextAsync(
@"D:\sample.txt",
Encoding.UTF8
);
Console.WriteLine(content);
}
}
Asynchronous reading is particularly useful in desktop applications, web applications, and services where blocking the current thread could delay other work.
Handle Missing Files and Read Errors
File-reading operations can fail when the path is incorrect, the file does not exist, access is denied, or another process has locked the file. Check the path and handle expected exceptions when the file comes from user input or an external source.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"D:\sample.txt";
try
{
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("The text file was not found.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("The application does not have permission to read the file.");
}
catch (IOException exception)
{
Console.WriteLine($"The file could not be read: {exception.Message}");
}
}
}
Choose the Right C# Text File Reading Method
| Method | Returned value | Use it when |
|---|---|---|
File.ReadAllText() | string | You need the entire file content at once. |
File.ReadAllLines() | string[] | You need all lines stored in an array. |
File.ReadLines() | IEnumerable<string> | You want to iterate through lines without loading them all at once. |
StreamReader.ReadLine() | One line at a time | You need detailed control over sequential reading. |
File.ReadAllTextAsync() | Task<string> | You need the full content without blocking the current thread. |
Common C# Text File Reading Issues
- Incorrect Windows path: use a verbatim string such as
@"D:\sample.txt"or escape backslashes as"D:\\sample.txt". - Wrong relative path: relative paths are resolved from the application’s current working directory, which may differ from the project directory.
- Unexpected characters: specify the correct encoding when the file is not encoded as expected.
- High memory usage: avoid
ReadAllText()andReadAllLines()for very large files when line-by-line processing is sufficient. - Unreleased file handles: dispose streams and readers with a
usingstatement.
C# Text File Reading FAQs
What is the simplest way to read a text file in C#?
Use File.ReadAllText(path) when the file is reasonably small and you need all its content in one string.
How do I read a large text file in C#?
Use File.ReadLines() or StreamReader.ReadLine() so the application processes one line at a time instead of loading the complete file into memory.
What happens when File.ReadAllText() cannot find the file?
It throws a FileNotFoundException. You can check File.Exists(path) before reading or catch the exception and report an appropriate error.
Does File.ReadLines() load the entire file into memory?
No. It reads lines as they are requested during enumeration, which makes it more memory-efficient for sequential processing.
How do I specify UTF-8 when reading a C# text file?
Pass Encoding.UTF8 to a method overload that accepts an encoding, such as File.ReadAllText(path, Encoding.UTF8), or pass it to the StreamReader constructor.
Conclusion
In this C# Tutorial, we learned how to read a text file as one string with File.ReadAllText(), process it line by line with StreamReader or File.ReadLines(), read content asynchronously, and handle common file-access errors.
TutorialKart.com