Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Directory doesn't update the Exists property to true

I have the following sample code.

private DirectoryInfo PathDirectoryInfo
{
    get
    {
        if (_directoryInfo == null)
        {
            // Some logic to create the path
            // var path = ...
            _directoryInfo = new DirectoryInfo(path);
        }
        return _directoryInfo;
    }
}

public voide SaveFile(string filename)
{
    if (!PathDirectoryInfo.Exists)
    {
         PathDirectoryInfo.Create();
    }

     // PathDirectoryInfo.Exists returns false despite the folder has been created.
     bool folderCreated = PathDirectoryInfo.Exists;  // folderCreated  == false

    // Save the file
    // ...
}

According to MSDN:

Exists property: true if the file or directory exists; otherwise, false.

Why Exists returns false after directory has been created? Am I missing something?

like image 206
ehh Avatar asked Apr 20 '16 07:04

ehh


1 Answers

You might change your property to this:

private DirectoryInfo PathDirectoryInfo
{
    get
    {
        if (_directoryInfo == null)
        {
            // Some logic to create the path
            // var path = ...
            _directoryInfo = new DirectoryInfo(path);
        }
        else
        {
            _directoryInfo.Refresh();
        }

        return _directoryInfo;
    }
}

That will ensure that you're always using current information whenever you get the property value.

That said, it wouldn't help you if you don't get the property value again in between. You are in your case though.

like image 200
jmcilhinney Avatar answered Nov 12 '22 23:11

jmcilhinney