开发者

Converting contents of HtmlTextWriter to a string

开发者 https://www.devze.com 2023-01-03 02:55 出处:网络
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 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( Ht开发者_如何学JAVAmlTextWriterAttribute.Src, src );
  output.RenderBeginTag( HtmlTextWriterTag.Img );
  output.RenderEndTag();
                <-- What is the HTML now? Maybe look in OnPreRenderComplete event?

  }


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.


This should work for you:

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

        string html = output.InnerWriter.ToString();

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号