What is the best way to store HtmlDocument to memory? Agility Pack for HTML

c# html-agility-pack


I am using HTML Agility Pack to parse and HTML document, make a change to a node, and then save the HTML document. I would like to save the document to memory so I can write the HTML out as a string later in the application. My current implementation always returns a string == "". I can see that the HtmlDocument object is not empty when debugging. Can someone provide some insight?

private string InitializeHtml(HtmlDocument htmlDocument)
        string currentUserName = User.Identity.Name;
        HtmlNode scriptTag = htmlDocument.DocumentNode.SelectSingleNode("//script[@id ='HwInitialize']");
        scriptTag.InnerHtml = 
            string.Format("org.myorg.application = {{}}; org.myorg.application.init ={{uid:\"{0}\", application:\"testPortal\"}};",currentUserName);

        MemoryStream memoryStream = new MemoryStream();
        StreamReader streamReader = new StreamReader(memoryStream);
        return streamReader.ReadToEnd();
6/28/2011 10:51:15 PM

Accepted Answer


memoryStream.Seek(0, System.IO.SeekOrigin.Begin)

Before creating the StreamReader and calling ReadToEnd()

The stream pointer is likely getting left at the end of the stream by the Save method (it's best practise for a component to do this - in case you want to append more data to the stream) therefore when you call ReadToEnd, it's already at the end and nothing gets read.

6/28/2011 11:05:59 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow