How can I save HtmlDocument to memory? Html Agility Pack

c# html-agility-pack

Question

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();
        htmlDocument.Save(memoryStream);
        StreamReader streamReader = new StreamReader(memoryStream);
        return streamReader.ReadToEnd();
    }

Accepted Answer

Try

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.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why