Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save HtmlDocument to memory? 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();
        htmlDocument.Save(memoryStream);
        StreamReader streamReader = new StreamReader(memoryStream);
        return streamReader.ReadToEnd();
    }
like image 786
Nick Avatar asked Jun 28 '11 22:06

Nick


1 Answers

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.

like image 195
Andras Zoltan Avatar answered Oct 03 '22 04:10

Andras Zoltan