[Download Source Code]
There is one problem that both Scott's code and my code run into: garbage collection! Over time, your view state might take a hundred megabytes of disk space and you will have to devise a way on how to clean it up. There are a few solutions on how to schedule the clean-up of the view state files but most of them have one thing in common.
The one thing in common is the clean up code. The code is rather simple and I have commented the code as well in a self explanatory fashion:
public sealed class CleanUpViewStateFiles {
private const int DaysToLeaveFiles = 2;</font>
<font face="Verdana" size="2"> /// <summary>
/// Cleans up all the files that are found in a given directory.
/// </summary>
/// <param name="path">
/// The absolute file path to the directory which contains the view state files.
/// </param>
public void CleanUp(string path) {
TimeSpan timeSpan = new TimeSpan(DaysToLeaveFiles, 0, 0, 0);
if (!path.EndsWith(@"\"))
path += @"\";
foreach (string filePath in Directory.GetFiles(path)) {
FileInfo file = new FileInfo(path + filePath);
// if the difference between now and the last access time is greater than the time span
// delete the file.
if (DateTime.Now.Subtract(file.LastAccessTime) >= timeSpan)
file.Delete();
}
}</font>
<font face="Verdana" size="2"> private CleanUpViewStateFiles() {}
}
I think it is a good period of keeping view state files for two days. Busier sites might want to reduce the amount the amount of time that the view state file stays on disk because those disks can get filled rather quickly.
I mentioned that there are a couple solutions to the clean-up. One of them is to implement a simple windows service that runs the common code every thirty minutes. Obviously, most of us do not have that type of control over the server (web or file server).
The other solution is, which I prefer, is to run one thread in the background. I do have some code on some "practice/honing sites" that runs a thread in the background that does the odd site maintenance (like keeping the ASP.NET application compiled so there are no delays). For an example of how to implement the ASP.NET-keep-alive, you may read Paul Wilson's article. And while you are at it, you may integrate the clean-up code into the keep-alive.
I have one tip: do not use the Global.asax approach -- HttpModule's will work just as well. In fact, even better because you will not be restricted by single inheritance. A sample of an HttpModule has been included in the downloadable source code - it is located in the CleanUpHttpModule.cs file. To set up the clean up module, this is what you configuration file should look something like this (I recommend that you put the clean up code and module in a seperate assembly):
<configuration>
<system.web>
<httpModules>
<add name="ViewStateCleanUp"
type="ViewStateToFS.CleanUpHttpModule, ViewStateToFS.dll"/>
</httpModules>
</system.web>
</configuration>