How to Delete a File in C#

Muhammad Maisam Abbas Feb 16, 2024
How to Delete a File in C#

This tutorial will introduce methods to delete a file at a specific path in C#.

Delete a File With the File.Delete(path) Function in C#

The File.Delete(path) function is used to delete the file inside the path path in C#. The following code example shows us how to delete a file from a specified path with the File.Delete() function in C#.

using System;
using System.IO;

namespace check_whether_a_file_exists {
  class Program {
    static void Main(string[] args) {
      string path = "C:\\filefolder\\file.txt";
      bool result = File.Exists(path);
      if (result == true) {
        Console.WriteLine("File Found");
        File.Delete(path);
        Console.WriteLine("File Deleted Successfully");
      } else {
        Console.WriteLine("File Not Found");
      }
    }
  }
}

Output:

File Found
File Deleted Successfully

We deleted a file inside the C:\\filefolder\\file.txt path with the File.Delete() function in C#. Our program first checks whether a file exists inside the path or not with the File.Exists() function. If the file exists, the program deletes the file with the File.Delete() function. If the file does not exist, the program displays File Not Found.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp File