William Walseth
William Walseth

Reputation: 2923

File Changes don't expire Cache

I'm attempting to cache XML files, using .NET Core 5.0.

I'm adapting the example from this page https://learn.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;
        }
    }

Upvotes: 1

Views: 262

Answers (1)

William Walseth
William Walseth

Reputation: 2923

I figured it out, hope this helps someone in the future.

I pass in a fully qualified file name like "d:\website\file.xml" as "strFileName". This is needed to properly load the XML.

However _fileProvider.Watch() method requires a relative URL, not a qualified file name, so in this case it needs to be "/file.xml".

So I convert "d:\website\file.xml" to "/file.xml" and call _fileProvider.Watch( "/file.xml" );

Upvotes: 1

Related Questions