How to delete a file in C#

The File class in the System.IO namespace provides the Delete() method to delete a file in C#. The Delete() method takes the path of the file as a string input and synchronously deletes the specified file.

Syntax

public static void Delete (string path);

This method will throw an appropriate exception when:

  • the input path is null, has invalid characters, or an empty string.
  • the input path is invalid.
  • the path is in use or there is an open handle on the file.
  • the path is too long, a directory, or a read-only file.
  • the path is an executable file.
  • the caller does not have the required permissions.

Code example

The code below demonstrates the deletion of file at a specified path.

Here, we are first creating a test file using the File.CreateFile() method, and then later deleting it using the File.Delete() method.

After the successful deletion of file, the program prints:

File /sample.txt is successfully deleted.
using System;
using System.IO;
class FileDeletion
{
public static void Main()
{
try
{
string filePath = "/sample.txt";
//create a file sample.txt in current working directory
if(!File.Exists(filePath))
{
File.Create(filePath);
}
// Delete the file
File.Delete(filePath);
if(!File.Exists(filePath))
{
Console.WriteLine($"File {filePath} is successfully deleted.");
}
}
catch (IOException e)
{
Console.WriteLine($"File could not be deleted:");
Console.WriteLine(e.Message);
}
}
}

Free Resources