Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange situation deleting and creating directories

Tags:

windows

I've got a strange situation where deleting and creating directories in quick succession on Windows Server 2008 results in some occasionaly strange errors. Sometimes I get IOExceptions, one time I have had a NotAuthorizedException.

Here is my code that works, but when stepping through in the debugger, lots of exceptions get thrown. In fact I've just had an IOException with 'the directory is not empty' while doing the directory.delete!

Update Quite a few of the responses talk about non atomic directory creation and delayed writes etc. Is there a 100% guaranteed way of making this work? Ideally I would like some system call that is 'DeleteDirectoryAndWaitForTheDirectoryToBeDeleted' and a corresponding system call that is 'CreateDirectoryAndWaitForTheDirectoryToBeCreated'.

Another update I took Neil's code below and tried it on my machine and it failed pretty quickly (after 20 loops). What appears to be happening is that the IDriveE Service has access to the directory and the attempt to create the directory fails with DELETE PENDING. I guess I need to do some more reasearch into things like DELETE PENDING.

Personally I don't like this code as it 'smells' wrong - but it works.

Console.WriteLine("CleanAndCreateDirectory: {0}", baseDirectory);
while (Directory.Exists(baseDirectory))
{
    Console.WriteLine("DeleteDirectory: {0}", baseDirectory);
    try
    {
        Directory.Delete(baseDirectory, true);
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
        Thread.Sleep(1000);
    }
}

while (!Directory.Exists(baseDirectory))
{
    try
    {
        Directory.CreateDirectory(baseDirectory);
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

My suspicions are something watching the file system that causes delays in some operations, but I've no idea what.

like image 963
Nick Randell Avatar asked Dec 31 '22 01:12

Nick Randell


2 Answers

When you delete an item from the file system it doesn't immediately delete it - it marks it for deletion at a later date (also if the directory contains sub-folders / files it will throw an exception).

like image 180
Mark Ingram Avatar answered Jan 07 '23 22:01

Mark Ingram


Windows also uses something called as 'Delayed Write'. So if you delete a directory its not deleted immediately and its just marked for deletion.

like image 33
Ankit Avatar answered Jan 07 '23 21:01

Ankit