There is already an accepted answer, but maybe someone finds it useful (or laugh at it if I missed something obvious again and completely lost my time)
I had the impression that File.Delete would either delete the file, or then return, or otherwise throw an exception - until I read this stream.
The Windows API mentions that by calling DeleteFile , the file is "marked for deletion when closing" because it allows deletion in an open file. After the file is marked for deletion, an attempt to open it will fail with the "Access denied" error. When the last handle to this file is closed, the file is actually deleted.
If windows actually delete the file before returning from the last CloseHandle call to the file, theoretically this code ensures that the file will be deleted below the using block:
using (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete)) { File.Delete(path); }
File.Open will fail if a file is opened in another process.
Note the difference in the fact that File.Delete even succeeds if the file does not exist (if the directory does not exist).
source share