C# Programming > Web

C# Encode URL

URL Encoding

Encoding a URL in C# is very easy thanks to the .NET Framework. Whether working on ASP.NET or desktop development, encoding internet URLs is important as very easy to do.

URL encoding simply refers to formatting a website address into a way that is readable by the HTTP protocols. That means eliminating special characters (such as #) and replacing them with their hexadecimal values (%23 for # for example).

While we could use an ASCII table to easily map symbol characters to their hexadecimal values, it would be time consuming to write such a C# function. This is were the .NET Framework built-in functions are very convenient.


If you are writing an ASP.NET page in C# and need to encode an URL, then it could not be easier. Every page has a Server property (which is an HttpServerUtility object) which has a UrlEncode function:



For C# desktop developers it is a bit trickier, but not impossible. Desktop developers need to use the UrlEncode static function in the HttpUtility class:


As you can see it's basically the same thing. However the problem is HttpUtility is found under the System.Web namespace. Yet, if you try to write System.Web.HttpUtility in a desktop application, it will not work.

To make it work, you have to manually add the System.Web.dll reference to your C# project. Simply go to Project > Add Reference in Visual Studio and select System.Web.dll from the .NET tab. The compiled application will not have any extra external dependencies, it is just a way to import the Web namespace into the desktop application.

So it might take an extra step, but it is just as easy to encode an URL string without having to do any extra work.

Back to C# Article List