How to delete a file in C#

By Tan Lee Published on Jun 11, 2024  437
In C#, you can delete a file using the File.Delete() method from the System.IO namespace.

Here's a code snippet deletes a file in C#.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.IO;
 
class Program
{
    static void Main()
    {
        // Specify the path of the file you want to delete
        string filePath = @"C:\path\yourfile.txt";
        try
        {
            // Check if the file exists before attempting to delete it
            if (File.Exists(filePath))
            {
                // c# delete the file
                File.Delete(filePath);
            }
            else
            {
                Console.WriteLine("File does not exist.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Make sure to replace "C:\path\yourfile.txt" with the actual path of the file you want to delete.