CodeBlanks Logo Icon CodeBlanks

File.ReadAllText

C# course · Intermediate · Lesson 100/116

Learn to read a text file all at once with File.ReadAllText.

Reading with File.ReadAllText

The File.ReadAllText method reads the entire content of a text file into a single string. It requires using System.IO;. Call: string text = File.ReadAllText("hello.txt");. If the file is missing, it throws FileNotFoundException.

This is the most practical way for small and medium files. Because the whole file is loaded into memory, very large files should use StreamReader instead. You can print the text with Console.WriteLine or split it into lines with Split.

Using and System.IO

File operations live in the System.IO namespace. Add using System.IO; at the top of your file. This lets you call File.ReadAllText, File.WriteAllText and similar methods directly.

File paths come in two flavors: relative (e.g. "data.txt") and absolute (e.g. "C:\\temp\\data.txt"). Backslashes are escaped: "\\". Forward slashes also work: "temp/data.txt" is cross-platform.

Exercise Read a file and print it

First create the file with File.WriteAllText("hello.txt", "Hello world");. Then read it back with File.ReadAllText and print with Console.WriteLine.

Show example solution
First write with File.WriteAllText("hello.txt", "Hello world");, then read with var text = File.ReadAllText("hello.txt");, finally print with Console.WriteLine(text);.
Example solution:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        File.WriteAllText("hello.txt", "Hello world");
        var text = File.ReadAllText("hello.txt");
        Console.WriteLine(text);
    }
}

Test yourself

  1. What does File.ReadAllText return?

    File.ReadAllText("a.txt")
    • string[] (array of lines)
    • string (single text)
    • byte[] (raw data)
    • StreamReader
    Show answer

    string (single text) — Correct. File.ReadAllText returns the whole file as a single string; split it into lines with Split.

  2. Complete the ReadAllText call

    string text = File.____("hello.txt");
    Show answer
    string text = File.ReadAllText("hello.txt");
  3. Match each method to its role

    ReadAllText
    Reads a single string
    WriteAllText
    Writes a single string
    ReadAllLines
    Reads an array of lines
    Exists
    Checks file exists

All lessons in Intermediate