I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
This time I would like a little helper class to your attention. When working in a web environment ever so often you need to encode/decode a Url or a piece of Html. In Silverlight you need to look for the System.Windows.Browser.HttpUtility class. The static System.Windows.Browser.HttpUtility class contains 4 static methods. A set for encoding and decoding Html and a set for encoding and decoding URLs.
The HttpUtility.HtmlEncode method converts all special Html characters to their encoded versions. Because html can’t display its control characters directly, they have to be converted to be displayed. An < character will be interpreted by Html as the start of an Html tag. To display it, it has to be encoded.
< is encoded into <
> is encoded into >
& is encoded into &
The counterpart of the HttpUtility.HtmlEncode method is the HttpUtility.HtmlDecode method. This method converts all encoded characters back to normal character.
When sending strings to urls, a lot of characters will cause misinterpretation on the receiving end. To replace this characters by their hexadecimal escape equivalents in a string you can use the HttpUtility.UrlEncode method. For example, an empty space is likely to cause trouble. After encode a string with a space, the space is replaced by %20.
To reverse the process and change the hexadecimal escape characters back to their normal form, you can use the HttpUtility.UrlDecode method.