CodeBlanks Logo Icon CodeBlanks

File.Exists and Delete

C# course · Intermediate · Lesson 104/116

Learn to check with File.Exists and delete with File.Delete.

Checking with File.Exists

The File.Exists method checks whether a file exists. It returns bool. Call: if (File.Exists("data.txt")) { ... }. If the file is missing, it returns false; no exception is thrown.

This is a standard pre-check in file operations. Calling Exists before ReadAllText prevents FileNotFoundException. In multi-threaded code, however, the file can be deleted between Exists and Read, so try/catch is still safer.

Deleting with File.Delete

The File.Delete method deletes a file. If the file is missing, no exception is thrown; it just continues. Call: File.Delete("old.txt");. Deleted files cannot be restored; use carefully.

Checking with Exists first is good practice, but since Delete does not throw when the file is missing, the check is not strictly required. To delete a directory use Directory.Delete; that is a separate topic.

Exercise Check, then delete

First create the file with File.WriteAllText("temp.txt", "data");. Then check with File.Exists("temp.txt") and print the result with Console.WriteLine. Finally delete the file with File.Delete("temp.txt"); and check again with File.Exists, printing the result.

Show example solution
First create with File.WriteAllText("temp.txt", "data");, then print Console.WriteLine(File.Exists("temp.txt"));, then File.Delete("temp.txt");, finally Console.WriteLine(File.Exists("temp.txt"));.
Example solution:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        File.WriteAllText("temp.txt", "data");
        Console.WriteLine(File.Exists("temp.txt"));
        File.Delete("temp.txt");
        Console.WriteLine(File.Exists("temp.txt"));
    }
}

Test yourself

  1. Complete the Exists call

    if (File.____("data.txt")) { Console.WriteLine("Yes"); }
    Show answer
    if (File.Exists("data.txt")) { Console.WriteLine("Yes"); }
  2. File.Delete on a missing file?

    File.Delete("missing.txt");
    • Throws FileNotFoundException
    • Returns false
    • Does nothing, no error
    • Creates the file
    Show answer

    Returns false — Correct. File.Delete does not throw on a missing file; it silently continues.

  3. Match each method to its behavior

    Exists
    Checks presence
    Delete
    Removes
    ReadAllText
    Reads
    WriteAllText
    Writes

All lessons in Intermediate