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
{ ... }
Delete(String) is an inbuilt File class method which is used to delete the specified file. Syntax: public static void Delete (string path);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With