How to delete a file in C#

By FoxLearn 6/11/2024 2:09:11 AM   197
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#.

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.