Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After executing File.Delete, the file remains in DELETE PENDING

Tags:

c#

io

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();
            }
        }
    }
}
like image 498
Ondrej Rozinek Avatar asked Apr 27 '15 09:04

Ondrej Rozinek


1 Answers

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.

like image 177
Alex Avatar answered Sep 21 '22 17:09

Alex