Does C# have an equivalent to JavaScript's encodeURIComponent()?
Uri.EscapeDataString
or HttpUtility.UrlEncode
is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow"
:
HttpUtility.UrlEncode("Stack Overflow")
-->"Stack+Overflow"
Uri.EscapeUriString("Stack Overflow")
-->"Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow")
--> Also encodes"+" to "%2b"
---->Stack%20%2B%20%20Overflow
Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
HttpUtility.HtmlEncode
/ Decode
HttpUtility.UrlEncode
/ Decode
You can add a reference to the System.Web
assembly if it's not available in your project
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!@#$%^&*()_+ some text here али мамедов баку";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this: !@#$%^&*()_+ some text here али мамедов баку
Thank You for attention