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.
public static void Delete (string path);
This method will throw an appropriate exception when:
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 directoryif(!File.Exists(filePath)){File.Create(filePath);}// Delete the fileFile.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);}}}