10.12.2006

Load text file into a string

This function loads a string from a text file and caches it using the System.Web caching object. I have to go track down this code snippet frequently. Thought I would post it here so I can find it later.

/// <summary>
///
    Load a text file from the file system
/// </summary>
///
<param name="filePath">File path of file to load</param>
///
<returns>Text file contents</returns>
protected string LoadFromFile(string filePath)
{
    
string fileContents = "";

    
// Load the content from a file and cache it
    if (HttpContext.Current.Cache[filePath] == null)
    {
        
// Load template from a file
        StreamReader reader = File.OpenText(filePath);
        fileContents = reader.ReadToEnd();
        reader.Close();

        
// Cache it
        System.Web.HttpContext.Current.Cache.Insert(filePath, fileContents, new CacheDependency(filePath));
    }
    
else
    {
        
// Read template from cache
        fileContents = (string) HttpContext.Current.Cache[filePath];
    }

    
return fileContents;
}        

No comments: