How to delete a file after checking whether it exists

Tom picture Tom · Jun 17, 2011 · Viewed 390.2k times · Source

How can I delete a file in C# e.g. C:\test.txt, although apply the same kind of method like in batch files e.g.

if exist "C:\test.txt"

delete "C:\test.txt"

else 

return nothing (ignore)

Answer

Adam Lear picture Adam Lear · Jun 17, 2011

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.