Summary#
Uri.EscapeDataString percent-encodes a string so it can be dropped safely into a URL. WebUtility.HtmlEncode
escapes a string so it can be dropped safely into HTML text. Both have inverses,
Uri.UnescapeDataString and WebUtility.HtmlDecode.
Signature#
Uri.EscapeDataString(<string> s) -> string
Uri.UnescapeDataString(<string> s) -> string
WebUtility.HtmlEncode(<string> s) -> string
WebUtility.HtmlDecode(<string> s) -> stringDescription#
URL escaping#
Uri.EscapeDataString keeps only the RFC 3986 unreserved characters — letters, digits, and - . _ ~ — and
percent-encodes everything else as UTF-8 bytes:
Uri.EscapeDataString("hello world") // "hello%20world"
Uri.EscapeDataString("a&b=c") // "a%26b%3Dc"
Uri.EscapeDataString("café") // "caf%C3%A9"That includes !, ', (, ) and *, which some URL encoders leave alone. Escaping the same string always
produces the same output, wherever the code runs.
Uri.UnescapeDataString reverses it, and is forgiving: a malformed escape is left exactly as written rather than
raising. Uri.UnescapeDataString("%zz") is "%zz", and a + is a literal plus, not a space.
HTML escaping#
WebUtility.HtmlEncode escapes the five characters that can break out of HTML text — ", &, ', <, > — and
renders every non-ASCII character as a numeric entity:
WebUtility.HtmlEncode("<script>alert('x')</script>")
// "<script>alert('x')</script>"Note that it does not escape +, /, ? or # — they are harmless in HTML text. It escapes for text, not
for an attribute value or a URL; do not use it to build a href, and do not use it as a substitute for the platform's
own output escaping, which already applies wherever a value is rendered.
Examples#
string SearchUrl(string term) {
return "/search?q=" + Uri.EscapeDataString(term);
}
// SearchUrl("blue & green") -> "/search?q=blue%20%26%20green"See also#
- Regex — pattern matching, which is likewise identical on both sides
- execution side — why escaping runs in the browser, with no round trip