Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 successfully?

Code:

FileInfo file = new FileInfo(openedPdfs.path);    
System.IO.File.Delete(openedPdfs.path);
if (file.Exists == false)
{ ... }
else 
{ ... }
like image 468
Guilherme Longo Avatar asked Jan 04 '13 16:01

Guilherme Longo


People also ask

Which method deletes the specified file in web framework?

Delete(String) is an inbuilt File class method which is used to delete the specified file. Syntax: public static void Delete (string path);

How will you delete an existing file?

Locate the file that you want to delete. Right-click the file, then click Delete on the shortcut menu. Tip: You can also select more than one file to be deleted at the same time. Press and hold the CTRL key as you select multiple files to delete.


1 Answers

As others have pointed out, the File.Delete method will throw an exception in case of failure.

What they omitted to point out is that the exception will be thrown in almost all cases but not in all cases. Specifically, the File.Delete method will not throw an exception if the file to be deleted did not happen to already exist. (Duh? What were they thinking?)

So, you should check if the file exists prior to deleting it; if it does not exist, you should not do anything. If it exists, you should invoke File.Delete, and if that throws an exception, then again, you should not do anything, because the file was not deleted. Otherwise, you should do your post-successful-deletion-of-existing-file stuff.

like image 96
Mike Nakis Avatar answered Sep 21 '22 05:09

Mike Nakis