Skip to content

CSharp Async FileIO ReadAllTextAsync

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Async: Reading Files with File.ReadAllTextAsync

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:


1. Example: asynchronously read a text 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.ReadAllTextAsync returns a Task<string>.
  • await is used to asynchronously get the result.
  • Exceptions are handled with try/catch.

2. Next steps

  • Use ReadAllLinesAsync or streams for large files.
  • Combine with LINQ to process the lines (CSharp-LINQ-Where-OrderBy.md).

Clone this wiki locally