CodeBlanks Logo Icon CodeBlanks

File.WriteAllText

C# course · Intermediate · Lesson 101/116

Learn to write a text file with File.WriteAllText.

Writing with File.WriteAllText

The File.WriteAllText method writes a text to a file. If the file does not exist, it is created; if it exists, its content is fully replaced. Call: File.WriteAllText("out.txt", "Line 1");. The second parameter is the text to write.

This method overwrites an existing file; the old content is lost. To append instead, use File.AppendAllText. When writing is done, the file is closed automatically; no extra close call is needed.

Appending with AppendAllText

The File.AppendAllText method appends text to the end of a file; the existing content is preserved. If the file does not exist, it is created. File.AppendAllText("log.txt", "New entry\n"); adds a new line each time.

For a line break use \n or Environment.NewLine. Environment.NewLine is cross-platform: \r\n on Windows, \n on Linux. AppendAllText is common for log files.

Exercise Write and read back

Write to a file with File.WriteAllText("data.txt", "Hot day"). Then read it back with File.ReadAllText and print with Console.WriteLine.

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

class Program
{
    static void Main()
    {
        File.WriteAllText("data.txt", "Hot day");
        var text = File.ReadAllText("data.txt");
        Console.WriteLine(text);
    }
}

Test yourself

  1. Complete the WriteAllText call

    File.____("out.txt", "Hello");
    Show answer
    File.WriteAllText("out.txt", "Hello");
  2. What does WriteAllText do to an existing file?

    • Appends to the content
    • Throws an error
    • Replaces the content completely
    • Cannot create a new file
    Show answer

    Cannot create a new file — Correct. WriteAllText replaces the existing content; the old content is lost.

  3. Match each method to its behavior

    WriteAllText
    Overwrites
    AppendAllText
    Appends
    ReadAllText
    Reads all
    Exists
    Checks existence

All lessons in Intermediate