Search code examples
c#html.nethtmltextwriter

How can I use HtmlTextWriter to write html comments?


I'm using HtmlTextWriter to output html to a stream. However, I'm missing a way 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 that does feel a bit inelegant - is there some built-in method I'm not seeing?


Solution

  • I can argue, after checking the specification, that these extensions could be marginally 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();
    }