I'm attempting to cache XML files, using .NET Core 5.0.
I'm adapting the example from this page https://docs.microsoft.com/en-us/aspnet/core/fundamentals/change-tokens?view=aspnetcore-5.0
I have the following code, that successfully caches the file (it doesn't load from disk every time), but when the file changes, the file content is not re-cached.
public XmlDocument loadXML(string strFileName) {
XmlDocument xml;
// Try to obtain the file contents from the cache.
if (_cache.TryGetValue(strFileName, out xml)) {
return xml;
}
xml = this.createNewDocument();
xml.Load(strFileName);
if (xml != null) {
var changeToken = _fileProvider.Watch(strFileName);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5))
.AddExpirationToken(changeToken);
// Put the file contents into the cache.
_cache.Set(strFileName, xml, cacheEntryOptions);
}
return xml;
}
}