# VBForums CodeBank > CodeBank - ASP / ASP.NET / MVC / Web API >  File Caching

## plenderj

The following code was born out of boredom on the DART this morning somewhere between Sydney Parade and Blackrock on my way to work. Its an enhanced version of my original file caching code that uses Cache Dependencies. Basically, if the file you've cached changes ASP.NET will remove the file from cache, so that the code can reload it on its next call.


VB Code:
Public Function strGetFile(ByVal strFilePath As String) As String
    Dim strRetVal As String = Cache(strFilePath)
    If strRetVal = vbNullString Then
        Response.Write("(Not Cached)")
        Dim objStreamReader As StreamReader = File.OpenText(strFilePath)
        strRetVal = objStreamReader.ReadToEnd()
        objStreamReader.Close()
        Dim objDepend As New Caching.CacheDependency(strFilePath)
        Cache.Insert(strFilePath, strRetVal, objDepend)
    Else
        Response.Write("(From Cache)")
    End If
    Return strRetVal
End Function

To demonstrate the usefulness of this code, try it out with a very large file, with code something like this:


VB Code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Response.Write("Start Time : " & Now & " ... ")
    strGetFile("c:\inetpub\wwwroot\WebApplication1\my_150_meg_file.txt")
    Response.Write("End Time : " & Now & " ... ")
End Sub

Simply create some large file somewhere, ensure the ASP.NET worker process has access to the folder and then browse to your ASPX page. Unless your system is lighning fast you'll see some delay before the page is displayed to the browser. ASP.NET has just loaded the file from the drive and cached it. You'll also see the time difference. Now try refreshing the page. ASP.NET has just loaded the file directly from cache.
If you modify the contents of the file in any way ASP.NET will remove it from cache and as such cause it to be reloaded from the drive on the next call.

The advantages and disadvantages are obvious. Advantages being faster page execution, and also extension of the lifespan of your disk drives. Disadvantage being that of memory usage - but hey, with no server shipping with less than 1GB of RAM these days, is that really an issue?

Happy Coding  :Smilie:

----------


## plenderj

For any generic purpose use:


VB Code:
Public Function strGetFile(ByVal strFilePath As String) As String
    Dim strRetVal As String = Cache(strFilePath)
    If strRetVal = vbNullString Then
        Dim objStreamReader As StreamReader = File.OpenText(strFilePath)
        strRetVal = objStreamReader.ReadToEnd()
        objStreamReader.Close()
        Cache.Insert(strFilePath, strRetVal, New Caching.CacheDependency(strFilePath))
    End If
    Return strRetVal
End Function

----------


## keanolou

well, try this one perhaps...

----------


## plenderj

... yes... indeed...

----------

