Search code examples
c#streamreadermemorystream

StreamReader reading MemoryStream to a string seems to be truncating end of file


I am saving an HTML document to a MemoryStream and then reading that stream (using StreamReader) out to a string object. HtmlDocument object is complete but when I inspect the string that is assigned from the streamReader.ReadToEnd() it appears that the end of the file has been truncated. I assume that my implementation of the MemoryStream or StreamReader is faulty. Can someone help me out?

HtmlDocument htmlDocument = GetDocument(htmlHref);
HtmlNode scriptTag = htmlDocument.DocumentNode.SelectSingleNode("//script[@id ='HwInitialize']");

scriptTag.InnerHtml =
    string.Format("org.myorg.application.init ={0};", stateJson);           

MemoryStream memoryStream = new MemoryStream();
htmlDocument.Save(memoryStream); //Save Document to memory
memoryStream.Seek(0, SeekOrigin.Begin);
StreamReader streamReader = new StreamReader(memoryStream);
return streamReader.ReadToEnd(); //return the stream contents to string

Solution

  • The htmlDocument.DocumentNode.OuterHtml property will serialize your htmlDocument, including any of your changes, into a html string.