8

I have a third party tool that creates an img tag through code using HtmlTextWriter's RenderBeginTag, RenderEndTag & AddAttribute methods. I want to get the resulting HTML into a string. I tried the reflection method mentioned here but I get a error "Unable to cast object of type 'System.Web.HttpWriter' to type 'System.IO.StringWriter". The InnerWriter type of the HtmlTextWriter is of type HttpWriter.

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

Addition: code from 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?

  }
Community
  • 1
  • 1
Tony_Henrich
  • 42,411
  • 75
  • 239
  • 374

2 Answers2

12
StringWriter w = new StringWriter();
HtmlTextWriter h = new HtmlTextWriter(w);

ctl.RenderControl(h);

return w.ToString();

Obviously, you got to close the connections properly. But it's roughly this; I had done this for unit testing, but I apologize, I don't have the exact code in front of me at the moment.

HTH.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • I don't have any controls. It's just an img tag created in code. Looking for solution starting from an existing HtmlTextWriter which uses an HttpWriter. – Tony_Henrich Jun 07 '10 at 18:39
  • Ok, then, could you post some code as to how you are working with the HttpWriter or HtmlTextWriter, so I can better advise? – Brian Mains Jun 07 '10 at 21:05
  • See my addition in the question. – Tony_Henrich Jun 07 '10 at 21:38
  • Ok, you can use my technique on any control to just get the HTML; you can have this code in the page code-behind even... if all you are looking for is to get HTML. If you want to override the HTML, you could try inheriting from their class, and overriding the render process. – Brian Mains Jan 13 '11 at 13:21
3

This should work for you:

        output.AddAttribute(HtmlTextWriterAttribute.Src, src);
        output.RenderBeginTag(HtmlTextWriterTag.Img);
        output.RenderEndTag();

        string html = output.InnerWriter.ToString();

Hope this helps.

philipproplesch
  • 2,127
  • 17
  • 20