Wednesday, June 17, 2026

C# Delete a file from a directory

File.Delete static method is used to delete a file from a directory.

Example
class Demo
{
    static void Main()
    {
        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string sourcePath = Path.Combine(documents, "sample.txt");
        try
        {
            if (File.Exists(sourcePath))
            {
                File.Delete(sourcePath);
                Console.WriteLine("File is deleted successfully.");
            }
            else
            {
                Console.WriteLine("File was not found.");
            }

        }
        catch (System.IO.IOException ex)
        {
            Console.WriteLine(ex.Message); // e.g. Access denied
        }
    }
}

No comments:

Post a Comment

Hot Topics