How to Delete a File in C#

C# Delete File

The File class in C# provides functionality to work with files. The File.Delete(path) method is used to delete a file in C#. The File.Delete() method takes the full path (absolute path including the file name) of the file to be deleted. If file does not exist, no exception is thrown.

Delete file in C#

The following code snippet deletes a file, Authors.txt stored in C:\Temp\Data\ folder.

File.Delete(@"C:\Temp\Data\Authors.txt"); 

The following code snippet is a .NET Core console app. The code example uses File.Exists method to check if the file exists. If yes, delete the file.

using System;
using System.IO;

namespace CSharpFilesSample {
    class Program {
        // Default folder    
        static readonly string rootFolder = @ "C:\Temp\Data\";    

        static void Main(string[] args) {
            // Files to be deleted    
            string authorsFile = "Authors.txt";

            try {
                // Check if file exists with its full path    
                if (File.Exists(Path.Combine(rootFolder, authorsFile))) {
                    // If file found, delete it    
                    File.Delete(Path.Combine(rootFolder, authorsFile));
                    Console.WriteLine("File deleted.");
                } else Console.WriteLine("File not found");
            } catch (IOException ioExp) {
                Console.WriteLine(ioExp.Message);
            }

            Console.ReadKey();
        }
    }
}

In the above code, the Path.Combine method is used to merge the folder and the file name to make it the absolute path. 

We can get all files in a folder using the Directory.GetFiles method and loop through each file and delete them. 

The following code snippet gets all files on the rootFolder and loop through the array and deletes all files in the folder.

// Delete all files in a directory    
string[] files = Directory.GetFiles(rootFolder);    
foreach (string file in files)    
{    
    File.Delete(file);    
    Console.WriteLine($"{file} is deleted.");    
}

Detailed tutorials:


Recommended Free Ebook
Similar Articles