How to Encode a String for a URL in C#
When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.
string rawText = "hello world!";
string encodedText = Uri.EscapeDataString(rawText);
Console.WriteLine(encodedText); // Output: hello%20world%21
This method encodes spaces as %20, making it ideal for query parameters.
For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:
using System.Web;
string encodedText = HttpUtility.UrlEncode("hello world!");
Console.WriteLine(encodedText); // Output: hello+world%21
For .NET Core and later, Uri.EscapeDataString() is the preferred choice.