Convert HtmlTextWriter content to string

I have a third-party tool that creates an img tag through code using the HtmlTextWriter RenderBeginTag, RenderEndTag and AddAttribute methods. I want to get the resulting HTML in a string. I tried the reflection method mentioned here , but I get the error “Unable to overlay object of type“ System.Web.HttpWriter ”on type“ System.IO.StringWriter. ”InnerWriter type HtmlTextWriter has type HttpWriter.

Any ideas on how to copy the html output file to a string?

Addition: code from a third-party control

protected override void Render( HtmlTextWriter output ) { ..... output.AddAttribute( HtmlTextWriterAttribute.Src, src ); output.RenderBeginTag( HtmlTextWriterTag.Img ); output.RenderEndTag(); <-- What is the HTML now? Maybe look in OnPreRenderComplete event? } 
+6
htmltextwriter
source share
2 answers
 StringWriter w = new StringWriter(); HtmlTextWriter h = new HtmlTextWriter(w); ctl.RenderControl(h); return w.ToString(); 

Obviously, you need to close the connections correctly. But it is something like this; I did this for unit testing, but I'm sorry, I do not have the exact code that is in front of me at the moment.

NTN.

+9
source share

This should work for you:

  output.AddAttribute(HtmlTextWriterAttribute.Src, src); output.RenderBeginTag(HtmlTextWriterTag.Img); output.RenderEndTag(); string html = output.InnerWriter.ToString(); 

Hope this helps.

+3
source share

All Articles