top of page

C Sharp

Public·2 members

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.

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(); 
     }  
    }   
   } 

67 Views
bottom of page