ehh*_*ehh 5 c# io directoryinfo fileinfo
我有以下示例代码。
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
// ...
}
Run Code Online (Sandbox Code Playgroud)
根据MSDN:
Exists属性:如果文件或目录存在,则为true;否则为false。否则为假。
创建目录后,为什么Exists返回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;
}
}
Run Code Online (Sandbox Code Playgroud)
这样可以确保您在获得属性值时始终使用最新信息。
就是说,如果您再也无法获得属性值,那将无济于事。不过,您的情况还是这样。
| 归档时间: |
|
| 查看次数: |
304 次 |
| 最近记录: |