Click to See Complete Forum and Search --> : HttpContext.Current.Caching and FileSystemWatcher


jamessadlier
December 13th, 2006, 06:51 AM
Hi,

I'm trying to store a list of files in the ASP.NET Cache object when my web application starts up. I then implement a FileSystemWatcher so that when the directory changes, I rebuild my array and reassign it to the Cache.

So my global.asax looks like ...


Private _fileSysWatcher As System.IO.FileSystemWatcher
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
AddFileListToCache()
Me._fileSysWatcher = New System.IO.FileSystemWatcher("c:\testfolder")
Me._fileSysWatcher.NotifyFilter = NotifyFilters.Size
Me._fileSysWatcher.EnableRaisingEvents = True
AddHandler _fileSysWatcher.Changed, AddressOf FileSystemNotify
End Sub

Private Sub FileSystemNotify(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
AddFileListToCache()
End Sub

Private Sub AddFileListToCache()
Dim files() As String = System.IO.Directory.GetFiles("c:\testfolder")
HttpContext.Current.Cache.Item("Files") = files
End Sub


It works fine when the application starts. However, when a new file gets added to the folder and the FileSystemWatcher is activated, an error occurs in AddFileListToCache(), because there is no HttpContext. The method was called by an IO event, rather than a HttpRequest, so the HttpContext is null.

Has anyone ever tried anything like this or got any better suggestions as to how to implement a caching object? I've already tried the following ...

1. Replacing the Cache object with the Application object, but same problem: the containing HttpContext object is null.

2. Implementing my own shared class with a Cache member variable. However, this doesn't work, as the Cache member variable always seems to throw a NullReferenceException when I attempt to use it anywhere other than in the current HttpContext (if anyone can explain this behaviour I'd be interested to hear why?).

Amy ideas?