Cache files using ASP.NET Cache Dependency

Posted by: Malcolm Sheridan , on 6/12/2009, in Category ASP.NET
Views: 72359
Abstract: The following article demonstrates how to use ASP.NET cache dependency with files.
Cache files using ASP.NET Cache Dependency
When it comes to getting the most performance out of your ASP.NET application, caching is one avenue to look into. Earlier this year I demonstrated how to use SQL Cache Dependency using SQL Server 2005 and 2008, but this time I’ll demonstrate how to cache files using ASP.NET Cache Dependency.
Caching files or directories for changes is made possible thanks to the System.Web.Caching.CacheDependency class. This class can monitor a single file and folder or an array of files and folders for changes. In this example I am using a single file in the webs ites root directory to monitor.
Open Visual Studio 2008 and create a new ASP.NET Web Application. Add a new text file to the root directory and call it SampleFile.txt. Open the text file and add the following text:
Donec fermentum condimentum nisi. Proin iaculis mauris id lorem viverra molestie. Duis vel orci. Et pulvinar pede ligula a sapien. Donec fermentum condimentum nisi. Proin iaculis mauris id lorem viverra molestie. Duis vel orci. Nam consequat. Morbi nec lacus
This is just some placeholder text. Next add a TextBox to the Default.aspx page and set the TextMode to MultiLine:
<asp:TextBox ID="TextBox1" runat="server" Width="312px" Height="188px"
In the page load event lets add the code that monitors the file for changes:
protected void Page_Load(object sender, EventArgs e)
    string fileContent = Cache["SampleFile"] as string;
    if (string.IsNullOrEmpty(fileContent))
        using (StreamReader sr = File.OpenText(Server.MapPath("~/SampleFile.txt")))
           fileContent = sr.ReadToEnd();
           Cache.Insert("SampleFile", fileContent, new System.Web.Caching.CacheDependency(Server.MapPath("~/SampleFile.txt")));
    TextBox1.Text = fileContent;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Dim fileContent As String = TryCast(Cache("SampleFile"), String)
      If String.IsNullOrEmpty(fileContent) Then
            Using sr As StreamReader = File.OpenText(Server.MapPath("~/SampleFile.txt"))
               fileContent = sr.ReadToEnd()
               Cache.Insert("SampleFile", fileContent, New System.Web.Caching.CacheDependency(Server.MapPath("~/SampleFile.txt")))
            End Using
      End If
      TextBox1.Text = fileContent
End Sub
As you can see in the example, the application checks the cache for an item in the cache named SampleFile and assigns the value to the fileContent variable. When you’re checking for values in the cache, it is important to create a reference to the cached object. This is important because the data in the cache can be removed at any time by the web server. Assigning it to a variable eliminates this problem. 
If the cache is null, the file is opened and added to the cache by the Cache.Insert method. The code shows an item named SampleFile added to the cache and having a file dependency set on the file named SampleFile.xml file. If you reload the page, the contents are read from the cache. If you update the contents of the SampleFile.txt file and reload the page, you’ll see that the object has been removed from the cache.
This is yet another way of using the cache to make your ASP.NET application perform that little better. The entire source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Kevin Clark on Sunday, July 19, 2009 9:48 AM
Hi, wonderfull article, however i should point out that cache has its limitations when it comes to <a href="">distributed caching</a>. if you want to know more read <a href="">here</a>.
Comment posted by Malcolm Sheridan on Saturday, August 8, 2009 5:26 AM
Yes you're quite right.  When you get two or more web servers you need to update your caching strategy.
Comment posted by Benny Blanco from the Bronx on Tuesday, October 29, 2013 9:24 AM
Excellent article...just need to clarify at the end that "the object has been removed from the cache" means if you change the SampleFile.txt the new contents of the file will be displayed in the textbox and next time from the cache until you change again the Samplefile.txt