Delete A File If Exists Using C#

Sameer Saini February 28, 2022
Delete A File If Exists Using C#

Sometimes we have a delete a file or create a new one but we are just not sure if there is already a file that exists?

In such a case, it's good practice to check if the file exists, and if it does, then delete the file.

Let's see how we can use two methods from the static class File that C# provides us.

var filePath = @"C:\ReadAllTextExample.txt"; if (File.Exists(filePath)) // Check if file exists { // Delete the file File.Delete(filePath); }

Let's see what happened in the above program.

We are first using the File.Exists method which takes a single parameter. This parameter is the string path of the file.

We are using it inside an if block as this File.Exists method returns a true or a false.

If the file exists, we will delete the file using the File.Delete method, which again takes only a single string path of file parameter.

If the file does not exist, we will come out of the if condition and nothing will happen.