This post will discuss how to delete a file using C#.

In C#, we can use the File.Delete() method for deleting a given file. It takes a single argument – relative or absolute path of the file to be deleted without any wildcard characters.

This method throws a DirectoryNotFoundException if the specified path is invalid and an IOException when the specified file is in use. It doesn’t throw an exception when a file deletion fails.

 
The following example first checks if a specified file exists using File.Exists. The File.Delete() method is called then if the file is present.

Download  Run Code

 
Since the File.Delete() method doesn’t throw an exception if the file doesn’t exist, there is no need to check for the file’s existence. We can simplify the code as follows:

Download  Run Code

 
We can also use an instance of the FileInfo class to delete a file in C#. Its Delete() method works similarly to the File.Delete() method discussed above.

Download  Run Code

 
To delete the directory and all its subdirectories, the Directory.Delete() method can be used, as demonstrated below:

Download  Run Code

That’s all about deleting a file with C#.