views:

247

answers:

2

I have some HTML text files that I would like to dynamically include in an ASP.NET page.

What is the best way to do this?

My first guess was to create a Literal control on the page and output as follows:

litMyLiteral.Text = System.IO.File.ReadAllText("c:\path\to\file.htm");

Is this a good solution, or is there a better one? For me, performance is a primary goal since these snippet files are output on every page on my site and there's a lot of traffic.

Thanks

+1  A: 

This would be a very bad solution as far as performance goes. Anything that initiates file IO on every single request is going to come back to haunt you later on if performance is a concern. A much better bet would be to create a cached dictionary that contains all of the content of all the text files that you want to include (assuming that there aren't overly many of them and they aren't overly huge) and storing all of the contents in memory so you don't have to open the file on every request. Other than that, the literal control approach isn't a bad idea, and is probably the simplest approach.

LorenVS
+2  A: 

Depending on how many files you have or how often you have to read them, I would suggest dynamically loading into the asp.net cache AS you need them and having some type of expiry or the cache.

Write some type of class to wrap you file access and caching implementaton. This code will probably work but don't use it as is, it's just to give you an idea of what I am talking about. Please not all the comments for improvements.

public static class StaticFiles
{
    public static string GetFile(string file)
    {
        // Note filename is the key
        if (Cache[file] != null)
        {
            // Return the cached data, this will be fast.
            return Cache[file].ToString();
        }
        else
        {
            // Make sure you do some exception checking / validation here for the
            // file data and don't hard code the path and make it relative assuming
            // it is in your application directory

            // Do you file access and store it with some type of expiry
            string output = System.IO.File.ReadAllText(string.Format("c:\path\to\{0}", file));
            Cache[file] = output;
            return output;
        }
    }
}

You should consider your cache expiry and see what would best suit your data. You could also implement some type of max check to allow a maximum number of cached files so the memory foot print doesn't get to big if you expiry is long. You really need to look at your total number of files and their size and figure out what would best suit your needs.

Kelsey