简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM