Safe URL Encoding in C# with `Uri.EscapeDataString()`: Handling Special Characters in URIs

Learn how to properly encode strings for use in URLs using C#'s `Uri.EscapeDataString()` method. This tutorial explains URL encoding (percent-encoding), demonstrates its use, and highlights its importance in creating valid and functional URIs, especially when dealing with user-supplied data.



Using C#'s `Uri.EscapeDataString()` Method for URL Encoding

The C# `Uri.EscapeDataString()` method encodes a string so it can be safely used as part of a URI (Uniform Resource Identifier) or URL. URL encoding, also known as percent-encoding, replaces special characters with a percentage sign (%) followed by a two-digit hexadecimal representation of the character's ASCII code. This is essential for creating valid and functional URLs, especially when dealing with user input or dynamic URL construction.

Understanding URL Encoding

URL encoding is crucial because certain characters (like spaces, punctuation, and reserved characters) have special meanings in URLs. Encoding these characters ensures that they are correctly interpreted and that the URL remains valid.

`Uri.EscapeDataString()` Syntax


public static string EscapeDataString(string str);

The method takes a string (`str`) as input and returns the URL-encoded version of that string.

Example 1: Encoding a Search Query


string searchQuery = "This is a test query";
string encodedQuery = Uri.EscapeDataString(searchQuery);
string url = $"https://www.example.com/search?q={encodedQuery}";
Console.WriteLine(url);

Example 2: Encoding an API Key


string apiKey = "MySecretKey123";
string encodedKey = Uri.EscapeDataString(apiKey);
string apiUrl = $"https://api.example.com/data?key={encodedKey}";
Console.WriteLine(apiUrl);

Handling Edge Cases

Note that `Uri.EscapeDataString()` doesn't encode certain characters that are allowed in URIs (letters, numbers, hyphens, underscores, periods). This can be beneficial in some cases but might require additional encoding for certain specific scenarios.


string myString = "This is a test string with spaces and special characters like & and =.";
string encodedString = Uri.EscapeDataString(myString);
Console.WriteLine(encodedString);