How is it possible that after calling File.Delete
the file still exists sometimes? I used simple code to reproduce the issue using File.Open
. The expected exception is FileNotFoundException
. I checked the operation in Process Monitor v3.05 and the result for the file is "DELETE PENDING" and throwns UnauthorizedAccessException
. Does anyone have an explanation for it?
public class Program
{
private const string DummyFileName = "dummy.txt";
private static void Main(string[] args)
{
int attempt = 0;
while (true)
{
using (File.Create(DummyFileName))
{
}
File.Delete(DummyFileName);
try
{
attempt++;
using (File.Open(DummyFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
}
catch (FileNotFoundException)
{
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("File exists{0}", File.Exists(DummyFileName));
Console.WriteLine("File remains in DELETE PENDING state in attempt {0}.", attempt);
Console.WriteLine(ex);
Console.ReadKey();
}
}
}
}
Windows allows a process to delete a file, even though it is still opened by another process (e.g. Windows indexing service or Antivirus). It gets internally marked as "delete pending". The file does not actually get removed from the file system, it is still there after the File.Delete call. Anybody that tries to open the file after that gets an access denied error. The file doesn't actually get removed until the last handle to the file object gets closed.
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