views:

322

answers:

2

My goal is to generate the aspx code of a page in the form of string.I am calling the below codebehind code through asynchronous request in javascript and i am getting the response back through Response.Write

        string html = string.Empty;
        using (var memoryStream = new MemoryStream())
        {
            using (var streamWriter = new StreamWriter(memoryStream))
            {
                var htmlWriter = new HtmlTextWriter(streamWriter);
                base.Render(htmlWriter);
                htmlWriter.Flush();
                memoryStream.Position = 0;
                using (var streamReader = new StreamReader(memoryStream))
                {
                    html = streamReader.ReadToEnd();
                    streamReader.Close();
                }
            }
        }
        Response.Write(html);
        Response.End();

I want to ask that is the above code is memory efficient, I am thinking of "yield" to use as it evaluates lazily.Can u suggest on memory efficency of above code.

+1  A: 

Your method stores an html copy at html variable, and another at memoryStream. Try this:

base.Render(new HtmlTextWriter(Response.Output));
Response.End();

While this can work, I'm not sure what are you trying to accomplish.

Rubens Farias
+2  A: 

Use a StringWriter instead of the MemoryStream, the StreamWriter and the StreamReader:

string html;
using (StringWriter stream = new StringWriter()) {
   using (HtmlTextWriter writer = new HtmlTextWriter(stream)) {
      base.Render(writer);
   }
   html = stream.ToString();
}
Response.Write(html);
Response.End();

The StringWriter uses a StringBuilder internally. The ToString method calls ToString on the Stringuilder, so it returns the internal string buffer as the string. That means that the string is only created once, and not copied back and forth.

Guffa