Why is DirectoryInfo.Exists true after deleting the directory?

2

In the following code

var Directory_02 = "TEST_01";

DirectoryInfo directory2 = new DirectoryInfo(Directory_02);
directory2.Create();

if (directory2.Exists)
{
    System.Console.WriteLine("{0} exists: {1}", Directory_02, directory2.Exists);
    directory2.Delete();
    System.Console.WriteLine("{0} exists: {1}", Directory_02, directory2.Exists);
}

We have the output

TEST_01 exists: True
TEST_01 exists: True

Why when directory2.Delete() is called directory2.Exists continues true ?

    
asked by anonymous 29.11.2017 / 02:21

2 answers

2

Searching a little more, I saw that the correct one would be to use

directory2.Refresh();

after

directory2.Delete();
    
29.11.2017 / 02:28
3

You need to reinstall the directory2 variable or call the Refresh() method after deleting it (or creating it).

directory2 = new DirectoryInfo(Directory_02); // reinstanciando
directory2.Refresh(); // ou atualizando...

If you look in DirectoryInfo.Exists source :

// Tests if the given path refers to an existing DirectoryInfo on disk.
// 
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists {
    [System.Security.SecuritySafeCritical]  // auto-generated
    get
    {
        try
        {
            if (_dataInitialised == -1)
                Refresh();
            if (_dataInitialised != 0) // Refresh was unable to initialise the data
                return false;

            return _data.fileAttributes != -1 && (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0;
        }
        catch
        {
            return false;
        }
    }
}

If you have ever checked if the directory exists (by changing the value of _dataInitialised ), it will always return that value, regardless of change unless you call Refresh() or build another object.     

29.11.2017 / 02:35