Javascript’s escape() in C# – a C# equivalent to the escape()-function

csharp_vs_javascriptThe .NET framework provides a large number of ways to encode HTML code and URLs. There exist, for example, Uri.EscapeDataString(), Uri.EscapeUriString(), System.Web.HttpUtility.UrlEncode(), System.Web.HttpUtility.UrlPathEncode(), System.Web.HttpUtility.HtmlEncode() or System.Web.HttpUtility.HtmlAttributeEncode().
However, if you are looking for equivalent functionality to Javascript’s escape(), so you will be disappointed by all of these aforementioned functions. None of these inherently with the .NET framework delivered functions is equivalent to the Javascript escape() function.  For better understanding, I made the following example:
The test text is in german, because the ‘ä’ is a nice character to show the problems. Translated to english it means: “Raffi’s annoying C# testcode”.

// Original source text
// Raffi’s ärgerlicher C# Teststring/Testcode.

// Javascript original (produced by escape())
// Raffi%27s%20%E4rgerlicher%20C%23%20Teststring/Testcode.

// Uri.EscapeDataString():
// Raffi’s%20%C3%A4rgerlicher%20C%23%20Teststring%2FTestcode.

// Uri.EscapeUriString():
// Raffi’s%20%C3%A4rgerlicher%20C#%20Teststring/Testcode.

// System.Web.HttpUtility.UrlEncode():
// Raffi%27s+%c3%a4rgerlicher+C%23+Teststring%2fTestcode.

// System.Web.HttpUtility.UrlPathEncode():
// Raffi’s%20%c3%a4rgerlicher%20C#%20Teststring/Testcode.

// System.Web.HttpUtility.HtmlEncode():
// Raffi's ärgerlicher C# Teststring/Testcode.

// System.Web.HttpUtility.HtmlAttributeEncode():
// Raffi's ärgerlicher C# Teststring/Testcode.

But I would not blog about it if I did not have a […]