Click here to Skip to main content
Licence CPOL
First Posted 28 Aug 2007
Views 98,300
Bookmarked 34 times

Full HTML Character Encoding in C#

By | 28 Aug 2007 | Article
This article shows how to take a String object and encode it as HTML using Unicode character entities for extended characters.

Introduction

This is my first CodeProject article, a short and sweet answer to a problem I couldn't find the solution to anywhere else.

Background

It is not terribly difficult to find a way to take a string containing HTML and "unescape" it to its proper characters (in fact HttpUtility.HtmlDecode() works perfectly). However, it's apparently another matter to take a complex string and escape it for HTML. At least, HttpUtility.HtmlEncode() doesn't fit the bill, as it only encodes the bare minimum of characters, ignoring such common things as curly quotes.

That said, of course, there's probably a better solution out there, so please direct me to it if you know of it, and I'll kindly remove or update this article accordingly.

Using the Code

The logic is quite simple. Basically, HTTP supports only standard ASCII characters for transmission, and extended characters are represented by named or numbered entity references. For example, the common ampersand (&) symbol is "escaped" as &. You can also use numbered entities, for example ® results in the registered (®) symbol.

Anyhow, the idea is to figure out what these numerical values are and manually encode extended characters (characters beyond 127, which are not standard ASCII) using the numbered entity format above.

The trick (hack) I discovered is simply to take a char and pass it to Convert.ToInt32(), which results in an apparently Unicode* value, which we can then convert to a string and wrap with the &# and ; characters.

* See Points of Interest below.

Here is the resulting method:

public static string HtmlEncode( string text ) {
    char[] chars = HttpUtility.HtmlEncode( text ).ToCharArray();
    StringBuilder result = new StringBuilder( text.Length + (int)( text.Length * 0.1 ) );

    foreach ( char c in chars ) {
        int value = Convert.ToInt32( c );
        if ( value > 127 )
            result.AppendFormat("&#{0};",value); 
        else
            result.Append( c );
    }

    return result.ToString();
}

Note that we call the built-in System.Web.HttpUtility.HtmlEncode() beforehand which is a prerequisite since it covers the encoding of ASCII-based control characters such as the ampersand (&) and less-than/greater-than symbols (<,>).

Points of Interest

This code is admittedly very hackish, however the only point of concern I have with it is ensuring that the numerical representation of the character is in fact standard Unicode values. In my tests, I found this to be the case, however I would like to guarantee it. If anyone knows the answer to this, please post a message in the comments and I'll update the article.

History

  • Aug 28, 2007 - First post
  • Aug 29, 2007 - Thanks to J4amieC for the StringBuilder optimization. I decided to start it off with a buffer of 10% on top of the passed string length, which should be more than enough for typical usage.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

chaiguy1337

President
The Little Software Company
Canada Canada

Member

My name is Logan Murray and I'm a Canadian. I'm interested primarily in C# and Windows desktop application development (learning WPF at the moment and then hopefully LINQ), though I hope to branch-out more to the web side of things eventually. I am the president and owner of The Little Software Company and am currently working on the Windows version of OrangeNote, to be released soon. Check out my RSS reader, FeedBeast™.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGreat PinmemberMember 77451735:09 27 Apr '11  
Generalamazing ! thanks so much Pinmemberdaniel7709:43 21 Feb '11  
GeneralThe same but as a method extension PinmemberGeni23:23 18 Feb '10  
GeneralPrevent conversion of HTML Tags Pinmembergibberishh1:19 13 Jan '10  
GeneralRe: Prevent conversion of HTML Tags Pinmemberchaiguy13376:50 13 Jan '10  
GeneralRe: Prevent conversion of HTML Tags Pinmembergibberishh17:54 14 Jan '10  
Generalnew lines, spacing [modified] Pinmembergordonmt11:47 9 Jun '09  
GeneralProperly Encoding for HTML PinPopularmemberJHankins6:50 4 Sep '07  
GeneralRe: Properly Encoding for HTML Pinmemberlogan13379:13 4 Sep '07  
GeneralUnicode point values Pinmemberjluber1:22 4 Sep '07  
GeneralRe: Unicode point values Pinmemberlogan13374:40 4 Sep '07  
GeneralNice and neat Pinmembercraigd10:21 3 Sep '07  
GeneralRe: Nice and neat Pinmemberlogan133711:19 3 Sep '07  
GeneralConvert.ToInt32() Pinmemberaprenot6:47 29 Aug '07  
GeneralRe: Convert.ToInt32() Pinmemberlogan13379:49 29 Aug '07  
QuestionNeed to call HttpUtility.HtmlEncode? PinmemberJcmorin1:40 29 Aug '07  
AnswerRe: Need to call HttpUtility.HtmlEncode? Pinmemberlogan13376:13 29 Aug '07  
GeneralString concatenation PinmvpJ4amieC22:39 28 Aug '07  
GeneralRe: String concatenation Pinmemberlogan13376:30 29 Aug '07  
GeneralRe: String concatenation [modified] PinmemberArjan Einbu23:15 3 Sep '07  
GeneralRe: String concatenation Pinmemberlogan13374:15 4 Sep '07  
Interesting. Yes it makes sense that the search would slow things down a little. I might update the article to reflect these findings. After all, a better algorithm is a better algorithm.
 
Could you explain the difference between tests C and D? They appear identical to me. Also don't forget the '#' sign after the ampersand; I'm pretty sure it's necessary to identify numerical entities.
AnswerRe: String concatenation PinmemberArjan Einbu12:19 4 Sep '07  
Questioncool, thank you, but reverse? Pinmembersekretar20:13 28 Aug '07  
AnswerRe: cool, thank you, but reverse? Pinmemberlogan13376:14 29 Aug '07  
Generalsize diff Pinmembersdachsvasor@hotmail.com18:42 28 Aug '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 28 Aug 2007
Article Copyright 2007 by chaiguy1337
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid