System.Web.HttpUtility.UrlEncode Method

Encodes a URL string.

Syntax

public static string UrlEncode (string str)

Parameters

str
The text to encode.

Returns

An encoded string.

Remarks

The HttpUtility.UrlEncode(string) method can be used to encode the entire URL, including query-string values. If characters such as blanks and punctuation are passed in an HTTP stream without encoding, they might be misinterpreted at the receiving end. URL encoding converts characters that are not allowed in a URL into character-entity equivalents; URL decoding reverses the encoding. For example, when the characters < and > are embedded in a block of text to be transmitted in a URL, they are encoded as %3c and %3e.

You can encode a URL using with the HttpUtility.UrlEncode(string) method or the HttpUtility.UrlPathEncode(string) method. However, the methods return different results. The HttpUtility.UrlEncode(string) method converts each space character to a plus character (+). The HttpUtility.UrlPathEncode(string) method converts each space character into the string "%20", which represents a space in hexadecimal notation. Use the HttpUtility.UrlPathEncode(string) method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

The HttpUtility.UrlEncode(string) method uses UTF-8 encoding by default. Therefore, using the HttpUtility.UrlEncode(string) method provides the same results as using the HttpUtility.UrlEncode(string, System.Text.Encoding) method and specifying System.Text.Encoding.UTF8 as the second parameter.

HttpServerUtility.UrlEncode(string) is a convenient way to access the HttpUtility.UrlEncode(string) method at run time from an ASP.NET application. Internally, HttpServerUtility.UrlEncode(string) uses the HttpUtility.UrlEncode(string) method to encode strings.

To encode or decode values outside of a web application, use the System.Net.WebUtility class.

Requirements

Namespace: System.Web
Assembly: System.Web (in System.Web.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0