This has been the bane of my existence for about 18 months. This macro from Cory Smith provides the best solution I've seen so far for this problem, outputting clean formatted code and to demo this...below is an example of my favourite piece of code d'jour (my reworking of the Server Side Viewstate stuff):
#region ServerSide ViewState handling code
// the extension is to protect users from sniffing in on view state via a simple
// HTTP request
private static string FilePathFormat = Global.Config.ViewStateServerPath + "{0}" + Global.Config.ViewStateFileExtension;
private const string ViewStateHiddenFieldName = "__ViewStateGuid";
// creates a new instance of a GUID for the current request
private string pViewStateFilePath = Guid.NewGuid().ToString();
/// <summary>
/// The path for this page's view state information (GUID based).
/// </summary>
public string ViewStateFilePath
{
get { return MapPath(String.Format(FilePathFormat, pViewStateFilePath)); }
}
/// <summary>
/// Saves the view state to the Web server file system.
/// </summary>
protected override void SavePageStateToPersistenceMedium(object viewState)
{
if (Global.Config.ServerBasedViewState)
{
// serialize the view state into a base-64 encoded string
LosFormatter los = new LosFormatter();
// save the view state to disk
StreamWriter sw = File.CreateText(ViewStateFilePath);
los.Serialize(sw, viewState);
sw.Close();
// saves the view state GUID to a hidden field
Page.RegisterHiddenField(ViewStateHiddenFieldName, pViewStateFilePath);
}
else
base.SavePageStateToPersistenceMedium(viewState);
}
/// <summary>
/// Loads the page's view state from the Web server's file system.
/// </summary>
protected override object LoadPageStateFromPersistenceMedium()
{
if (Global.Config.ServerBasedViewState)
{
string vsGuid = Request.Form[ViewStateHiddenFieldName];
string vsString = MapPath(String.Format(FilePathFormat, vsGuid));
if (!File.Exists(vsString))
throw new Exception("The Viewstate file " + vsString + " is missing!!!");
else
{
// instantiates the formatter and opens the file
LosFormatter los = new LosFormatter();
StreamReader sr = File.OpenText(vsString);
string viewStateString = sr.ReadToEnd();
// close file and deserialize the view state
sr.Close();
return los.Deserialize(viewStateString);
}
}
else
return base.LoadPageStateFromPersistenceMedium();
}
#endregion
Pretty huh!