Why is Directoryinfo.Exists true after deleting the directory?

Asked

Viewed 44 times

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 exit

TEST_01 exists: True
TEST_01 exists: True

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

2 answers

3

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

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

If you look at the source code of DirectoryInfo.Exists:

// 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 ever you have checked if the directory exists (by changing the value of _dataInitialised), it will always return that value, regardless of change unless called Refresh() or build another object.

2


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

directory2.Refresh();

after the

directory2.Delete();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.