views:

131

answers:

1

In ASP.NET I would like to store an object in the cache which has a dependancy on all the files in specific folder and its sub-folders. Just adding the object with a dependancy on the root folder doesn't work. Is there in any reasonable way to do this other than creating a chain of dependancies on all the files?

+1  A: 

I believe you can roll your own cache dependency and use FileSystemMonitor to monitor the filesystem changes.

Update: Sample code below

public class FolderCacheDependency : CacheDependency
{
    public FolderCacheDependency(string dirName)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(dirName);
        watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
        watcher.Created += new FileSystemEventHandler(watcher_Changed);
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
    }

    void watcher_Renamed(object sender, RenamedEventArgs e)
    {
        this.NotifyDependencyChanged(this, e);
    }

    void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        this.NotifyDependencyChanged(this, e);
    }
}
Ramesh
Does FileSystemWatcher raise events when a file in that directory is changed? FileSystemWatcher watch and entire tree or just the top-level?
AnthonyWJones
@AnthonyWJones - you can use IncludeSubdirectories to include or exclude them. You may find issues due to multiple events fired. Check out http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
Ramesh