Search code examples
.nethtmlencodinghtml-escape-characters

.Net Method for converting String to HTML Escape Characters


I want to convert an e-mail address into HTML Escape Characters as a basic way to try and avoid being harvested by spam-bots. Like mentioned in this question:

When placing email addresses on a webpage do you place them as text like this:

[email protected]

or use a clever trick to try and fool the email address harvester bots? For example:

HTML Escape Characters:

joe.somebody@company.com

I cannot find a .Net method to do so though. The Html.Encode only does the invalid HTML characters such as £$%^& and not letters.

Does a method exist or do I need to write my own?

Many Thanks


Solution

  • I'm not aware of anything included in the framework, but you could try something like this?

    public string ConvertToHtmlEntities(string plainText)
    {
        StringBuilder sb = new StringBuilder(plainText.Length * 6);
        foreach (char c in plainText)
        {
            sb.Append("&#").Append((ushort)c).Append(';');
        }
        return sb.ToString();
    }