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();
}
Try
Before creating the
StreamReaderand callingReadToEnd()The stream pointer is likely getting left at the end of the stream by the
Savemethod (it’s best practise for a component to do this – in case you want to append more data to the stream) therefore when you callReadToEnd, it’s already at the end and nothing gets read.