How can I use the HtmlEncode (or HtmlDecode) function in Visual Studio (vb.net)?

Austin Burk picture Austin Burk · Dec 22, 2011 · Viewed 46.3k times · Source

I'm making an application that involves logging into a server, however, the post data needs some encoding.

Dim strEncUsername As String = Server.HtmlEncode(Me.txtUsername.Text)

However, since this isn't an asp.net application, this doesn't work. How the hay am I supposed to do this? I tried looking for an Imports thing, but no real luck.

Answer

davidsleeps picture davidsleeps · Dec 22, 2011

If you add a reference to System.Web to your project you can use the following to html encode your string

Dim strEncUsername As String = System.Web.HttpUtility.HtmlEncode(Me.txtUsername.Text)

MSDN Documentation for HttpUtility.HtmlEncode

Edit
Screenshot of intellisense showing HtmlEncode:
Screenshot of intellisense showing HtmlEncode

Screenshot of references in project:
Screenshot of references in project

Output from application:

unsafe text: <em>evil em tags within</em>
safe text: &lt;em&gt;evil em tags within&lt;/em&gt;