How can I use HtmlTextWriter to write html comments?

I am using HtmlTextWriter

to output html to stream. However, I am missing the ability to write html comments. Of course, I could write an extension method doing

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
  writer.Write("<!-- ");
  writer.WriteEncodedText(comment);
  writer.Write(" -->");
}

      

But this feels a bit inelegant - is there some built-in method I can't see?

+3


source to share


1 answer


I can argue, after checking the spec , that these extensions might be slightly more correct,



public static void WriteBeginComment(this HtmlTextWriter writer)
{
    writer.Write(HtmlTextWriter.TagLeftChar);
    writer.Write("!--");
}

public static void WriteEndComment(this HtmlTextWriter writer)
{
    writer.Write("--");
    writer.Write(HtmlTextWriter.TagRightChar);
}

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
    if (
        comment.StartsWith(">") || 
        comment.StartsWith("->") || 
        comment.Contains("--") ||
        comment.EndsWith("-"))
    {
        throw new ArgumentException(
            "text does not meet HTML5 specification",
            "comment");
    }

    writer.WriteBeginComment();
    writer.Write(comment);
    writer.WriteEndComment();
}

      

+2


source







All Articles