c sharp

C# URL Encode and Decode

URL encoding and decoding are the methods used to transform the special characters or non-alphanumeric letters in a URL into a syntax that can be properly communicated and understood by internet browsers and servers. To conduct the URL encoding and decoding in C#, utilize the System.Web.HttpUtility class from the System.Web library. The act of substituting the restricted and hazardous letters in a URL with their appropriate percent-encoded equivalents is known as URL encoding. Reversal URL encoding and translating the percent-encoded data back to their initial letters and numbers is known as URL decoding.

Within this guide today, we will discuss some C# code snippets to perform the URL encoding and decoding most simply and easily as possible.

Syntax:

Here is the general C# code syntax to perform encoding on any URL:

string encodedString = HttpUtility.UrlEncode(inputString);
  • The HttpUtility is a class from the System.Web namespace.
  • The UrlEncode is a static method of the HttpUtility class.
  • The inputString is the string that you want to URL encode.
  • The method returns the URL-encoded string.

The following line of code displays the general C# syntax for decoding any encoded URL:

string decodedString = HttpUtility.UrlDecode(inputString);
  • The HttpUtility is a class from the System.Web namespace.
  • The UrlDecode is a static method of the HttpUtility class.
  • The inputString is the URL-encoded string that you want to decode.
  • The method returns the decoded string.

Example 1: C# URL Encoding

By performing the C# encoding, you can be confident that a URL won’t become invalid when it’s supplied as an argument or as a component of a request. The HttpUtility.UrlEncode function in C# may be used to encode the URLs as discussed in the “Syntax” section. Therefore, we initiate a new C# code example to demonstrate how decoding works in C# for URLs or string values.

Let’s dive into the explanation of the following attached C# code snippet. The code begins by importing the necessary namespaces of C# using the “using” directives. It includes the “System” and “System.Web” which are required for the code to work with the HttpUtility class. It’s important to note that the code relies on the HttpUtility class from the “System. Web” namespace. Therefore, ensure that your project has a reference to the “System.Web.dll” assembly to access this class successfully.

The code defines a class named “Test” that contains a “Main” method which is necessary to start and execute any program processing.

Inside the “Main” method, a string mutable named “str” is stated and set with the “C Sharp !” value. The HttpUtility.UrlEncode method is invoked, passing the “str” variable as an argument. This URL method encodes the provided string and returns the encoded version. The result of the URL encoding is stored in another string variable named “res”. Finally, the encoded “res” string is printed to the console using “Console.WriteLine”.

using System;
using System.Web;
class Test {
  static void Main() {
    string str = "C Sharp !";
    string res = HttpUtility.UrlEncode(str);
    Console.WriteLine(res);
    }
}

When you execute this code, it outputs the URL-encoded version of the original string. In this case, the output is “C%20Sharp%20%21”. The UrlEncode method replaces the space character with %20 and the exclamation mark with %21 to ensure that the string can be safely transmitted and interpreted in a URL.

Example 2: C# URL Decoding

The HttpUtility.UrlDecode function in C# may be used to decode a URL-encoded text. Therefore, the provided code is a simple C# console application that demonstrates the URL decoding using the “WebUtility.UrlDecode” method.

Let’s start the explanation of this code. The code begins with the necessary “using directives” – the using “System” and using “System.Net;” – which import the required namespaces for the program. Inside the “Test” class, there is a static “Main” method that is necessary to process any C# code.

Within the “Main” method, again, the “str” string mutable is stated and adjusted with the “C%20Sharp%20%21” value. This string represents a URL-encoded version of the “C Sharp !” text where %20 embodies a space and %21 denotes an exclamation mark. The “WebUtility.UrlDecode” method is invoked, passing the “str” variable as an argument. This method decodes the URL-encoded string and returns the decoded version. The decoded string value is allocated to the “res” mutable.

using System;
using System.Net;
class Test {
  static void Main()  {
    string str = "C%20Sharp%20%21";
    string res = WebUtility.UrlDecode(str);
        Console.WriteLine(res);
    }
}

Finally, the decoded string is printed to the console using Console.WriteLine(res) which displays the original “C Sharp !” text since it has been successfully URL decoded.

Example 3:

Let’s have our last example of this article that demonstrates the usage of URL decoding and HTML encoding/decoding using the System.Net.WebUtility class within the C# program.

The program starts with the declaration of a string variable URL which contains a URL-encoded string: “https%3A%2F%2Fwww.test.com%2F%3Fq%3Dcsharp”. This URL contains special characters that have been percent-encoded.

Next, the program is called WebUtility.UrlDecode(url) to decode the URL. The decoded URL is assigned to the “du” string variable. This function replaces the percent-encoded values with their corresponding characters. In this case, it decodes the URL to “https://www.test.com/?q=csharp”. The program prints the decoded URL using the “Console.WriteLine”.

Next, the program declares another string variable which is “htm” that contains an HTML string: “<h1>C-Sharp Program!</h1>”. To demonstrate the HTML encoding, the program calls the WebUtility.HtmlEncode(htm) to encode the HTML string. The encoded HTML is assigned to the string variable, “eh”. This function replaces the special characters in the HTML string with their corresponding character entities.

In this case, it encodes the HTML to “&lt;h1&gt;C-Sharp Program!&lt;/h1&gt;”. The program prints the encoded HTML using the Console.WriteLine. Lastly, the program declares another string variable “eht” that contains an HTML-encoded text: “&lt;h2&gt;C Sharp!&lt;/h2&gt;”. To demonstrate the HTML decoding, the program calls the WebUtility.HtmlDecode(eht) to decode the HTML-encoded text. The decoded text is assigned to the “dht” string variable. This function replaces the character entities in the HTML-encoded text with their corresponding characters. In this case, it decodes the text to “<h2>C Sharp!</h2>”.

using System;
using System.Net;
class Test {
  static void Main()  {
        string url = "https%3A%2F%2Fwww.test.com%2F%3Fq%3Dcsharp";
        string du = WebUtility.UrlDecode(url);
        Console.WriteLine("Decoded URL: " + du);
        string htm = "<h1>C-Sharp Program!</h1>";
        string eh = WebUtility.HtmlEncode(htm);
        Console.WriteLine("Encoded HTML: " + eh);
        string eht = "&lt;h2&gt;C Sharp!&lt;/h2&gt;";
        string dht = WebUtility.HtmlDecode(eht);
        Console.WriteLine("Decoded HTML Text: " + dht);

        }

 }

The program prints the decoded HTML text within the following C# editor using the “Console.WriteLine” statement of C# as per the code snippet that is attached previously:

Conclusion

While dealing with URL encoding and decoding, it’s crucial to manage the exceptions and any mistakes to guarantee the appropriate processing of input strings and avoid any unforeseen consequences. It’s important to note that you may need to include a reference to the “System” if you are using the “.NET Core” or “.NET 5+”. To utilize the HttpUtility class, use the web NuGet package.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.