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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp File

  • Write a Stream to a File in C#
  • Rename a File in C#