๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# File Basics

A file stores text on disk after a program ends. The File class writes and reads a whole file as one string.

Write and read a file

WriteAllText stores the string first. ReadAllText then loads the stored text back.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        File.WriteAllText("notes.txt", "Hello from a file");
        string text = File.ReadAllText("notes.txt");
        Console.WriteLine(text);
    }
}

Append a second line

AppendAllText adds text after the content already stored. The read shows both lines.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        File.WriteAllText("log.txt", "First line\n");
        File.AppendAllText("log.txt", "Second line");
        string text = File.ReadAllText("log.txt");
        Console.WriteLine(text);
    }
}

Check a file exists

Exists answers true for a file that was written. It answers false for a name that was never used.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        File.WriteAllText("present.txt", "here");
        Console.WriteLine("Present: " + File.Exists("present.txt"));
        Console.WriteLine("Missing: " + File.Exists("absent.txt"));
    }
}

Example

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            string text = File.ReadAllText("missing.txt");
            Console.WriteLine(text);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("That file is not there");
        }
    }
}

Key points

  • using System.IO brings in the File class.
  • File.WriteAllText writes a string to a file.
  • WriteAllText creates the file when it is missing.
  • WriteAllText replaces the old content when the file exists.
  • File.ReadAllText reads the whole file into one string.
  • File.AppendAllText adds text to the end of a file.
  • File.Exists answers true when a file is there.

In this example, the program tries to read a file that was never written. The read throws a FileNotFoundException. The catch block prints a line written by the program itself.

Note

These examples use plain file names, so each file sits beside the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does File.ReadAllText return?