Does C# have an equivalent to JavaScript's encodeURIComponent()?
Solution 1
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)
Solution 2
HttpUtility.HtmlEncode
/ Decode
HttpUtility.UrlEncode
/ Decode
You can add a reference to the System.Web
assembly if it's not available in your project
Solution 3
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
Solution 4
System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.
Solution 5
Try Server.UrlEncode()
, or System.Web.HttpUtility.UrlEncode()
for instances when you don't have access to the Server
object. You can also use System.Uri.EscapeUriString()
to avoid adding a reference to the System.Web
assembly.
Related videos on Youtube
travis
Software engineer at Tenet in Rochester, NY. he/him My keybase: keybase.io/trav
Updated on December 29, 2020Comments
-
travis over 3 years
In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
Is there an equivalent for C# applications? For escaping HTML characters I used:
txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"&#" + ((int)m.Value[0]).ToString() + ";");
But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:
txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"%" + String.Format("{0:x}", ((int)m.Value[0])));
Returns "
%a9%221a"
for"©√"
instead of"%C2%A9%E2%88%9A"
. It looks like I need to split the string up into bytes or something.Edit: This is for a windows app, the only items available in
System.Web
are:AspNetHostingPermission
,AspNetHostingPermissionAttribute
, andAspNetHostingPermissionLevel
. -
travis over 15 yearsI should've been more specific: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.
-
David Thibault over 15 yearsYou can add a reference to the System.Web assembly
-
travis over 15 yearsThe Server object is inaccessible from a windows app
-
travis over 13 yearsThe main issue I was having was not having a reference to System.Web in my solution, but I wasn't aware of EscapeUriString, thanks!
-
jwaliszko about 12 yearsIn contrast to encodeURIComponent(), Uri.EscapeUriString() doesn't encode "+" to "%2b". Use Uri.EscapeDataString() instead.
-
Toland Hon about 10 yearsUri.EscapeUriString() didn't do anything for me, but I was able to properly url-encode the strings using Uri.EscapeDataString()
-
Steven De Kock over 8 yearsUse WebUtility instead of HttpUtility to avoid having to reference System.Web. HttpUtility doesn't exist in .NET Core.
-
Brandon Paddock about 8 yearsHtmlEncoding is an entirely different thing. UrlEncode is a non-sensical API which should never be used. It doesn't make sense to encode an entire URL (unless you actually want to encode its value to use as a parameter - but that's not what this does). The point of encoding/escaping is that you're conveying that a reserved character should be passed through without its usual meaning (e.g. that ? identifies the query, or & separates query parameters). This requires knowledge that UrlEncode does not and cannot have.
-
Timo over 7 years@Steve Would you consider making your last paragraph bold? It seems to be the most important thing to know on this page, and it needs more visibility.
-
mklement0 over 7 yearsWorks, but you can simply use
Uri.EscapeDataString("!@#$%^&*()_+ some text here али мамедов баку")
instead. -
mklement0 over 7 years@TolandHon: Indeed. The reason is that
Uri.EscapeUriString()
corresponds to JavaScript'sencodeURI()
- which preserves URI-reserved chars. such as/
,&
, ... as-is (plus#
), whereas - as you've discovered, it isUri.EscapeDataString()
that corresponds to JavaScript'sencodeURIComponent()
. -
Jason about 7 yearsAlso see this answer for more explanation on the difference between Uri.EscapeUriString and Uri.EscapeDataString: stackoverflow.com/questions/4396598/…
-
Jason about 7 yearsSee this answer for more explanation on the difference between HttpUtility.UrlEncode and HttpUtility.UrlPathEncode stackoverflow.com/questions/4145823/…
-
nothingisnecessary about 7 years
UrlPathEncode
andEscapeUriString
do not encode ampersand&
butUri.EscapeDataString
andHttpUtility.UrlEncode()
do -
Øystein Kolsrud over 4 yearsActually,
Uri.EscapeDataString
encodes the characters '(' and ')' whileHttpUtility.UrlEncode
does not. -
omostan about 2 yearsKudos to Steve for providing this excellent answer and Tim for the edited version. This work well and save my nerves after a very long search. To all of you who always contribute to this very useful platform, I say thank you!