-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Async FileIO ReadAllTextAsync
Joe Care edited this page Dec 22, 2025
·
1 revision
This lesson extends the async/await topic with a simple file I/O example.
Related wiki pages:
- Async basics:
CSharp-AsyncAwait-Basics.md - Exceptions:
CSharp-Exceptions-TryCatch.md
Official docs:
- File helpers: https://learn.microsoft.com/dotnet/api/system.io.file
using System;
using System.IO;
using System.Threading.Tasks;
class Example
{
public static async Task Main(string[] args)
{
string filePath = "data.txt"; // adjust path as needed
try
{
string content = await ReadFileAsync(filePath);
Console.WriteLine("File content:");
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
catch (Exception ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
}
}
static async Task<string> ReadFileAsync(string filePath)
{
return await File.ReadAllTextAsync(filePath);
}
}Key points:
-
File.ReadAllTextAsyncreturns aTask<string>. -
awaitis used to asynchronously get the result. - Exceptions are handled with
try/catch.
- Use
ReadAllLinesAsyncor streams for large files. - Combine with LINQ to process the lines (
CSharp-LINQ-Where-OrderBy.md).