URL Encoding in C#: Complete Guide
In C#, you can achieve URL encoding using the System.Web.HttpUtility.UrlEncode method. This method is located in the System.Web namespace and requires the System.Web assembly to be referenced.
The following is an example of using the HttpUtility.UrlEncode method for URL encoding.
using System;
using System.Web;
class Program
{
static void Main()
{
string url = "https://www.example.com/?q=你好世界";
string encodedUrl = HttpUtility.UrlEncode(url);
Console.WriteLine(encodedUrl);
}
}
The output result is: https%3a%2f%2fwww.example.com%2f%3fq%3d%e4%bd%a0%e5%a5%bd%e4%b8%96%e7%95%8c
The HttpUtility.UrlEncode method encodes special characters in a string so that they can be used as part of a URL.