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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With