Guilherme Longo Guilherme Longo - 2 months ago 11
C# Question

How to check if System.IO.File.Delete deleted a file sucessfully

After removing a file using the system.io.file class:

System.IO.File.Delete(openedPdfs.path);


I need to run some code if the file was sucessfully deleted.
As long as the method does not return any value, I am checking if the file exist after the delete method. If it still exist I supposed the operation had failed.

The problem is, the deletion method works fine, but there is a couple of seconds to the file to be deleted. The Exist function return true because at the time it is checking the file is there.

How can I verify for sure if the
System.IO.File.Delete(openedPdfs.path);
completed sucessfully ?

Code:

FileInfo file = new FileInfo(openedPdfs.path);
System.IO.File.Delete(openedPdfs.path);
if (file.Exists == false)
{ ... }
else
{ ... }

Answer

Delete should throw an exception if the file wasn't deleted. Hence, your call to Exists is redundant.

Have a look at the documentation for Delete.

Comments