This is a pattern I use frequently -- for example, if I have rendered some RSS format search results to a page, I may want to save this generated HTML of the DataList (or a Gridview, or any other UI display control) to a file, which can easily be read back in later and assigned to an HtmlGeneric Control that is then attached to a placeholder on an ASPX page, kind of like a FileSystem Caching mechanism:
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
StreamWriter sr = null;
string fullFilePath = Server.MapPath("mySavedDataList1.htm");
sr = new StreamWriter(fullFilePath);
string oStuff = oStringWriter.ToString();
catch (Exception ex)
// Exception Handler here
if (sr != null)
What this does is wrap an HtmlTextWriter around a StringWriter, then call the RenderControl method of the control whose contents we want to save, into the HtmlTextWriter. We then create a StreamWriter into our file path, call the ToString() method on the StringWriter to get out our content, and using the StreamWriter, we write the content to the file.
Later on, if there is a request for this specific content, instead of having to go to our database or make our WebClient search all over again, we can simply look to see if we have cached the content on the filesystem. If so, we only need to load it and display it.