While calling File.Delete(file_path) for a file which is opened in another process, the attempt fails with cannot access error, but on exiting the app (from where the attempt was made) the file gets deleted automatically. After File.Delete attempt, the path gets inaccessible for any other operation.
I need to either fail on delete and let the path be accessible through the app or delete the file completely, not on app exit.
Well my code is this :
private bool DeleteFilesAsync(string FileToDelete)
{
try
{
//Set file's attribute to normal if it is ReadOnly file
File.SetAttributes(FileToDelete, FileAttributes.Normal);
File.Delete(FileToDelete);
//Some bussiness logic to update file's status in database
return true;
}
catch (Exception ex)
{
//log the error
return false;
}
}
Something wrong here?
Windows does have a delete-on-last-close feature. All deletes are handled that way. The only reason that this almost never occurs in practice is because most apps do not open the file with
FILE_SHARE_DELETEso it is not possible to delete a used file. But at the Kernel level all deletes are delete-on-close.There might be a way to clear the delete flag by calling
NtSetInformationFileto set theFileDispositionInfoclass. This assumes that it is possible to clear the delete flag. It might well be.Anyway, a more sane approach would be to open the file before deleting it to ensure that exclusive access is available:
After this line passes without exception, we know that the file was unused at the point of opening it. Of course, it might be opened by someone else immediately after this line, but maybe this solution is enough for you.