C# escaping text
last modified November 15, 2026
This article shows how to escape text in C# for HTML, URLs, regular expressions, JSON, and XML. Each context has its own metacharacters and its own encoder, and using the wrong one leaves a hole or produces text that the receiver cannot read.
Escaping replaces characters that have a special meaning in a
format with a representation that carries the same text but no special
meaning. In HTML, < starts a tag; in a regular expression,
+ means repetition; in JSON, a double quote ends a string. The
replacement is not encryption and it is not compression: it is a reversible
mapping defined by the target format.
The safe rule is to escape at the boundary where the text enters the other
format, and to decode only when the text leaves it. A value should be stored
and passed around in its plain form. Escaping it early, then escaping it
again for the next layer, produces double-encoded text such as
< that appears literally in the output.
HTML
WebUtility.HtmlEncode converts text into HTML-safe content by
replacing &, <, >, the
double quote, and the single quote. It is part of
System.Net and does not require ASP.NET Core.
HtmlDecode reverses the transformation.
using System.Net;
string input = "<script>alert('x & y')</script>";
string encoded = WebUtility.HtmlEncode(input);
Console.WriteLine(encoded);
Console.WriteLine(WebUtility.HtmlDecode(encoded));
The encoded form no longer contains a tag or an ampersand, so a browser shows the text instead of running the script. Decoding the result returns the original input.
string encoded = WebUtility.HtmlEncode(input);
The method encodes the five characters that can change the structure of an
HTML document. A single quote becomes ', which matters
when text is placed inside an attribute written with single quotes. The
method does not make arbitrary text safe for a <script>
element or a style block; those contexts need JavaScript or CSS
escaping, not HTML encoding.
$ dotnet run
<script>alert('x & y')</script>
<script>alert('x & y')</script>
URLs
A URL has reserved characters: ? starts the query,
& separates parameters, # starts the fragment,
and % introduces an escape. A value placed into a URL must have
those characters percent-encoded. Uri.EscapeDataString does this
for a single component such as a query value or a path segment.
using System.Net; string query = "C# & .NET"; string escaped = Uri.EscapeDataString(query); Console.WriteLine(escaped); Console.WriteLine(Uri.UnescapeDataString(escaped)); Console.WriteLine(WebUtility.UrlEncode(query));
The value contains a hash, a space, an ampersand, and a period.
EscapeDataString encodes the reserved characters and leaves the
period alone.
string escaped = Uri.EscapeDataString(query);
The result C%23%20%26%20.NET can be appended to a query string
without changing its structure. WebUtility.UrlEncode produces
C%23+%26+.NET: it encodes a space as +, which is
the convention for application/x-www-form-urlencoded form data,
not for a general URL. Use EscapeDataString for components of a
URI and UrlEncode for form posts.
$ dotnet run C%23%20%26%20.NET C# & .NET C%23+%26+.NET
Regular expressions
In a regular expression, characters such as ., *,
+, ?, (, ),
[, and ] have special meanings. When a pattern
must match a user-supplied string literally, escape the string before
building the pattern. Regex.Escape does that.
using System.Text.RegularExpressions;
string input = "a+b (literal)";
string pattern = Regex.Escape(input);
Console.WriteLine(pattern);
Console.WriteLine(Regex.IsMatch(input, pattern));
Console.WriteLine(Regex.IsMatch("aab", pattern));
The escaped pattern matches the literal text a+b (literal) and
does not match aab, which the unescaped pattern would accept.
string pattern = Regex.Escape(input);
Regex.Escape prefixes the metacharacters with a backslash and
escapes a literal space as \ . It is intended for the pattern,
not for the replacement string. In a replacement, $1 and
$& have special meaning; use a
MatchEvaluator or escape the replacement according to the
Regex.Replace rules.
$ dotnet run a\+b\ \(literal\) True False
JSON
JSON strings are delimited by double quotes and use backslash escapes for
control characters and quotes. System.Text.Json handles this
automatically. Its default encoder goes further and escapes
HTML-sensitive characters such as <, >, and
&, so a JSON document can be embedded in a web page without
closing a surrounding <script> element.
using System.Text.Encodings.Web;
using System.Text.Json;
string input = "<b>Tom & Jerry</b>";
Console.WriteLine(JsonEncodedText.Encode(input));
Console.WriteLine(JsonSerializer.Serialize(input));
var relaxed = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
Console.WriteLine(JsonSerializer.Serialize(input, relaxed));
JsonEncodedText.Encode returns the escaped characters without
the surrounding quotes. JsonSerializer.Serialize adds the quotes
and uses the same encoder by default. The relaxed encoder leaves the HTML
characters as they are.
Console.WriteLine(JsonSerializer.Serialize(input, relaxed));
The default output replaces <, >, and
& with \u003C, \u003E, and
\u0026. That looks noisy, but it prevents a string containing
</script> from terminating an inline script block. Use
UnsafeRelaxedJsonEscaping only when the JSON is not embedded in
HTML or XML and the receiver accepts the raw characters. The name is a
warning, not a suggestion.
$ dotnet run \u003Cb\u003ETom \u0026 Jerry\u003C/b\u003E "\u003Cb\u003ETom \u0026 Jerry\u003C/b\u003E" "<b>Tom & Jerry</b>"
XML
XML has the same five predefined entities as HTML plus rules for element and
attribute names. An XmlWriter escapes text and attribute values
as it writes them, which is safer than concatenating strings with
< and &.
using System.Text;
using System.Xml;
var builder = new StringBuilder();
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartElement("message");
writer.WriteString("<hello & goodbye>");
writer.WriteEndElement();
}
Console.WriteLine(builder);
The text passed to WriteString contains angle brackets and an
ampersand. The writer emits them as entities, so the document remains
well-formed.
writer.WriteString("<hello & goodbye>");
WriteString escapes character data; the same happens for
attribute values passed to WriteAttributeString. Do not build
XML with string interpolation and then try to patch the result: the escaping
depends on whether the text lands in an element, an attribute, or a comment,
and XmlWriter tracks that context for you.
$ dotnet run <message><hello & goodbye></message>
Choosing the right encoder
Escaping is context-specific. The same string needs different treatment in an HTML body, an HTML attribute, a URL query, a JavaScript string, a JSON document, and an XML element. A single generic "sanitize" function cannot cover all of them, and applying two encoders in a row usually produces text that displays the escapes instead of the original characters.
Keep values in their raw form for as long as possible, encode once when writing them into a format, and decode once when reading them back. For SQL, do not escape quotes by hand; use parameters, which send the value separately from the statement. For HTML built from user input, HTML encoding is the first line of defense, but a dedicated sanitizer is still needed if the input may contain markup that should be preserved.
The Encoding, Base64, and regular expressions tutorials cover the related text transformations. Base64 is an encoding for binary data, not an escaping mechanism for HTML or URLs.
Source
How to customize character encoding with System.Text.Json
In this article we have escaped text for HTML, URLs, regular expressions, JSON, and XML. See also the Encoding, Base64, regular expressions, and JSON tutorials.
Author
List all C# tutorials.