我想使用FileSystemInfo.Refresh()
这个函数..但是我想知道如果我们调用这个函数会发生什么。
2 回答
MSDN - FileSystemInfo.Refresh
Refreshes the state of the object.
The reason to call is to get "latest" properties of the file. The original object may have stale data if information was updated on disk. I.e. MSDN explicitly calls out attribute case:
Calls must be made to Refresh before attempting to get the attribute information.
Sample showing staleness:
// create a file at this location
var fileName = @"E:\Temp\attr.txt";
var fi = new FileInfo(fileName);
Console.WriteLine("Attributes: {0}", fi.Attributes); // Archive
var fi2 = new FileInfo(fileName);
fi2.Attributes = fi2.Attributes | FileAttributes.ReadOnly;
Console.WriteLine("New Attributes: {0}", fi2.Attributes); // Archive, ReadOnly
Console.WriteLine("Stale attributes: {0}", fi.Attributes); // Archive
fi.Refresh();
Console.WriteLine("Refreshed attributes: {0}",fi.Attributes);// Archive, ReadOnly
来自MSDN;
FileSystemInfo.Refresh 从当前文件系统获取文件的快照。
在尝试获取属性信息之前,必须调用 Refresh,否则信息将过时。
它明确地使用File.FillAttributeInfo
which 是内部方法。
public void Refresh()
{
this._dataInitialised = File.FillAttributeInfo(this.FullPath, ref this._data, false, false);
}
您可以检查File.FillAttributeInfo(String, WIN32_FILE_ATTRIBUTE_DATA&, Boolean, Boolean)
Method的工作原理。
来自https://stackoverflow.com/a/1448727/447156
FileInfo 值只加载一次,然后缓存。要获取当前值,请在获取属性之前调用 Refresh()
你也可以检查这个问题;