创建目录不会将 Exists 属性 更新为 true
Creating Directory doesn't update the Exists property to true
我有以下示例代码。
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
// ...
}
根据MSDN:
Exists property: true if the file or directory exists; otherwise, false.
为什么创建目录后存在 returns false?我错过了什么吗?
您可以将 属性 更改为:
private DirectoryInfo PathDirectoryInfo
{
get
{
if (_directoryInfo == null)
{
// Some logic to create the path
// var path = ...
_directoryInfo = new DirectoryInfo(path);
}
else
{
_directoryInfo.Refresh();
}
return _directoryInfo;
}
}
这将确保您在获得 属性 值时始终使用当前信息。
就是说,如果您在这期间没有再次获得 属性 值,这对您没有帮助。不过你是你的情况。
我有以下示例代码。
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
// ...
}
根据MSDN:
Exists property: true if the file or directory exists; otherwise, false.
为什么创建目录后存在 returns false?我错过了什么吗?
您可以将 属性 更改为:
private DirectoryInfo PathDirectoryInfo
{
get
{
if (_directoryInfo == null)
{
// Some logic to create the path
// var path = ...
_directoryInfo = new DirectoryInfo(path);
}
else
{
_directoryInfo.Refresh();
}
return _directoryInfo;
}
}
这将确保您在获得 属性 值时始终使用当前信息。
就是说,如果您在这期间没有再次获得 属性 值,这对您没有帮助。不过你是你的情况。