How to Delete a File in C#

The code example in this article shows how to delete a file in C#. Also code example of how to delete all files in a folder using 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.

  1. 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.

  1. using System;    
  2. using System.IO;    
  3.     
  4. namespace CSharpFilesSample    
  5. {    
  6. class Program    
  7. {    
  8. // Default folder    
  9. static readonly string rootFolder = @"C:\Temp\Data\";    
  10.     
  11. static void Main(string[] args)    
  12. {    
  13. // Files to be deleted    
  14. string authorsFile = "Authors.txt";    
  15.     
  16. try    
  17. {    
  18. // Check if file exists with its full path    
  19. if (File.Exists(Path.Combine(rootFolder, authorsFile)))    
  20. {    
  21. // If file found, delete it    
  22. File.Delete(Path.Combine(rootFolder, authorsFile));    
  23. Console.WriteLine("File deleted.");    
  24. }    
  25. else Console.WriteLine("File not found");    
  26. }    
  27. catch (IOException ioExp)    
  28. {    
  29. Console.WriteLine(ioExp.Message);    
  30. }    
  31.     
  32. Console.ReadKey();    
  33. }    
  34. }    
  35. }

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.

  1. // Delete all files in a directory    
  2. string[] files = Directory.GetFiles(rootFolder);    
  3. foreach (string file in files)    
  4. {    
  5. File.Delete(file);    
  6. Console.WriteLine($"{file} is deleted.");    
  7. }
Detailed tutorials: