How to delete a file after checking whether it exists How to delete a file after checking whether it exists windows windows

How to delete a file after checking whether it exists


This is pretty straightforward using the File class.

if(File.Exists(@"C:\test.txt")){    File.Delete(@"C:\test.txt");}


As Chris pointed out in the comments, you don't actually need to do the File.Exists check since File.Delete doesn't throw an exception if the file doesn't exist, although if you're using absolute paths you will need the check to make sure the entire file path is valid.


Use System.IO.File.Delete like so:

System.IO.File.Delete(@"C:\test.txt")

From the documentation:

If the file to be deleted does not exist, no exception is thrown.


You could import the System.IO namespace using:

using System.IO;

If the filepath represents the full path to the file, you can check its existence and delete it as follows:

if(File.Exists(filepath)){     try    {         File.Delete(filepath);    }     catch(Exception ex)    {      //Do something    } }